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 into Sets of K=4 Consecutive NumbersInput Array:12334456k = 4Grouping Process:Group 1: [1, 2, 3, 4]Group 2: [3, 4, 5, 6]✓ All numbers used exactly onceResult: true
Understanding the Visualization
1
Input
Array [1,2,3,3,4,4,5,6] with k=4
2
Process
Group into consecutive sequences of length k
3
Output
Return true if possible, false otherwise
Key Takeaway
🎯 Key Insight: Always start forming groups from the smallest available number to ensure optimal grouping without conflicts
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