702813. Min Subsets with Consecutive Numbers
Easy
Min Subsets with Consecutive Numbers
Summary
Given a list of integers, find all subsets that contain consecutive numbers. The problem is to identify these subsets and return them as output.
Detailed Explanation
The problem can be solved using a straightforward approach. First, sort the input array in ascending order. Then, iterate through the sorted array and maintain a set of consecutive numbers found so far. If the current number is one more than the last number in the set, add it to the set. Otherwise, start a new subset.
Here's a step-by-step breakdown:
- Sort the input array
numsin ascending order. - Initialize an empty list
resultto store the subsets of consecutive numbers. - Iterate through the sorted array:
- If the current number is one more than the last number in the set, add it to the set.
- Otherwise, start a new subset and add the current number to it.
- Add each subset to the
resultlist. - Return the
resultlist.
Time complexity: O(n log n) due to sorting Space complexity: O(1) as we only use a constant amount of space
Here's an ASCII art diagram representing the process:
+---------------+
| nums |
| [1, 2, 3, 5, 6] |
+---------------+
|
|
v
+---------------+
| sorted nums |
| [1, 2, 3, 5, 6] |
+---------------+
|
|
v
+---------------+
| result |
| [[1, 2], [2, 3], [3, 5], [5, 6]] |
+---------------+
Optimized Solutions
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static List<List<Integer>> minSubsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
int start = nums[0];
List<Integer> subset = new ArrayList<>();
for (int num : nums) {
if (num == start + 1) {
subset.add(num);
start++;
} else {
result.add(subset);
subset = new ArrayList<>();
subset.add(num);
start = num;
}
}
result.add(subset);
return result;
}
}