#3659
Partition Array Into K-Distinct Groups
MediumArrayHash TableCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Count the frequency of each element. If the number of unique elements is less than k or if the total number of elements isn't divisible by k, it's impossible to form the groups.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each element in nums.
- 2Step 2: Check if the number of unique elements is at least k and if the total count of elements is divisible by k.
- 3Step 3: If both conditions are satisfied, return true; otherwise, return false.
solution.py5 lines
1from collections import Counter
2
3def can_partition(nums, k):
4 freq = Counter(nums)
5 return len(freq) >= k and len(nums) % k == 0ℹ
Complexity note: Counting frequencies takes linear time, and storing them requires linear space.
- 1The number of unique elements must be at least k.
- 2Total elements must be divisible by k.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.