#1296

Divide Array in Sets of K Consecutive Numbers

Medium
ArrayHash TableGreedySortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal approach uses a hash map to count occurrences of each number and then iteratively builds sets of k consecutive numbers. This is efficient because we only traverse the array a few times, making it faster than the brute-force method.

⚙️

Algorithm

5 steps
  1. 1Step 1: Check if the length of the array is divisible by k; if not, return false.
  2. 2Step 2: Count the occurrences of each number using a hash map.
  3. 3Step 3: Iterate through the sorted keys of the hash map, and for each key, try to form a set of k consecutive numbers.
  4. 4Step 4: If a set can be formed, decrement the counts in the hash map accordingly.
  5. 5Step 5: If all numbers are used up correctly, return true; otherwise, return false.
solution.py14 lines
1# Full working Python code
2from collections import Counter
3
4def canDivideIntoSets(nums, k):
5    if len(nums) % k != 0:
6        return False
7    count = Counter(nums)
8    for num in sorted(count):
9        while count[num] > 0:
10            for i in range(k):
11                if count[num + i] <= 0:
12                    return False
13                count[num + i] -= 1
14    return True

Complexity note: The time complexity is O(n log n) due to the sorting step, and the space complexity is O(n) because we store the counts of the numbers in a hash map.

  • 1The array must be divisible by k to form complete sets.
  • 2Using a hash map allows for efficient counting and checking of consecutive numbers.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.