Divide Array in Sets of K Consecutive Numbers - Problem

Given an array of integers nums and a positive integer k, determine whether it's possible to divide the array into sets of k consecutive numbers.

Return true if it's possible to divide the array into such sets, otherwise return false.

Example: If nums = [1,2,3,3,4,4,5,6] and k = 4, we can form two sets: [1,2,3,4] and [3,4,5,6], so return true.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,3,4,4,5,6], k = 4
Output: true
💡 Note: We can form two groups of 4 consecutive numbers: [1,2,3,4] and [3,4,5,6]. Each number is used exactly once.
Example 2 — Impossible Case
$ Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
Output: false
💡 Note: We have 12 numbers, so we need 4 groups of 3. However, we can't form 4 complete consecutive sequences due to the gap at 9,10,11.
Example 3 — Single Group
$ Input: nums = [1,2,3,4], k = 4
Output: true
💡 Note: Perfect case: exactly one group of 4 consecutive numbers [1,2,3,4].

Constraints

  • 1 ≤ k ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Divide Array in Sets of K Consecutive Numbers INPUT nums array (unsorted) 1 2 3 3 4 4 5 6 Group size k = 4 Frequency Count: 1 --> 1 2 --> 1 3 --> 2 4 --> 2 5 --> 1 6 --> 1 Total: 8 elements ALGORITHM STEPS 1 Count Frequencies Build HashMap of counts 2 Sort Unique Keys Process smallest first 3 Greedy Selection Form k consecutive groups 4 Validate Groups Check all elements used Greedy Process: Start at 1: Form [1,2,3,4] OK Next min = 3: Form [3,4,5,6] OK All counts = 0 Division possible! FINAL RESULT Successfully divided into 2 groups: Group 1 1 2 3 4 Group 2 3 4 5 6 Output: true 8 elements / k=4 = 2 complete groups Key Insight: Greedy approach works because we always start forming groups from the smallest available number. This ensures consecutive sequences are formed optimally. If any number lacks k-1 consecutive successors with sufficient counts, division is impossible. Time: O(n log n), Space: O(n). TutorialsPoint - Divide Array in Sets of K Consecutive Numbers | Greedy Approach
Asked in
Amazon 45 Google 38 Facebook 32 Microsoft 28
78.9K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen