Divide Array in Sets of K Consecutive Numbers - Problem
Can you organize a deck of cards into perfect consecutive sequences?
Given an array of integers
For example, if you have
Goal: Return
Key constraints: Each number must be used exactly once, and each group must contain exactly k consecutive integers.
Given an array of integers
nums and a positive integer k, your task is to determine whether it's possible to divide this array into groups of exactly k consecutive numbers.For example, if you have
[1, 2, 3, 6, 2, 3, 4, 7, 8] and k = 3, you need to check if you can form groups like [1, 2, 3], [2, 3, 4], and [6, 7, 8] using all numbers exactly once.Goal: Return
true if such a division is possible, false otherwise.Key constraints: Each number must be used exactly once, and each group must contain exactly k consecutive integers.
Input & Output
example_1.py โ Basic consecutive groups
$
Input:
nums = [1,2,3,3,4,4,5,6], k = 4
โบ
Output:
true
๐ก Note:
We can divide the array into two groups: [1,2,3,4] and [3,4,5,6]. Each group has exactly 4 consecutive numbers.
example_2.py โ Impossible division
$
Input:
nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
โบ
Output:
true
๐ก Note:
We can form groups: [1,2,3], [2,3,4], [3,4,5], and [9,10,11]. All groups have exactly 3 consecutive numbers.
example_3.py โ Array length not divisible by k
$
Input:
nums = [1,2,3,4], k = 3
โบ
Output:
false
๐ก Note:
Array length (4) is not divisible by k (3), so it's impossible to divide into groups of size 3.
Visualization
Tap to expand
Understanding the Visualization
1
Count Your Cards
First, count how many of each card value you have
2
Start from Smallest
Always begin forming sequences from the smallest available card
3
Form Complete Sequences
Create groups of exactly k consecutive cards
4
Remove Used Cards
Remove cards from your pile as they're used in sequences
5
Repeat Until Done
Continue until all cards are used or impossible to proceed
Key Takeaway
๐ฏ Key Insight: The greedy approach of always starting from the smallest available number is optimal because it ensures we never waste opportunities to form valid consecutive sequences.
Time & Space Complexity
Time Complexity
O(n log n)
O(log n) per insertion/deletion in TreeMap, O(n) total operations
โก Linearithmic
Space Complexity
O(n)
TreeMap stores at most n unique numbers with their counts
โก Linearithmic Space
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 109
- 1 โค k โค nums.length
- Each number in nums can be used exactly once
- Groups must contain exactly k consecutive integers
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code