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:

  1. Sort the input array nums in ascending order.
  2. Initialize an empty list result to store the subsets of consecutive numbers.
  3. 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.
  4. Add each subset to the result list.
  5. Return the result list.

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

View on GeeksforGeeks
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;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.