#846
Hand of Straights
MediumArrayHash TableGreedySortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal 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 frequency map to count occurrences of each card and then attempts to form groups by checking if the required consecutive cards are available. This is efficient because we avoid unnecessary searches and directly manage counts.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each card using a HashMap.
- 2Step 2: Sort the unique keys of the HashMap.
- 3Step 3: Iterate through the sorted keys and for each key, try to form a group of consecutive cards by checking and decrementing their counts in the HashMap.
solution.py14 lines
1# Full working Python code
2
3def canArrange(hand, groupSize):
4 from collections import Counter
5 if len(hand) % groupSize != 0:
6 return False
7 count = Counter(hand)
8 for card in sorted(count.keys()):
9 if count[card] > 0:
10 for i in range(groupSize):
11 if count[card + i] < count[card]:
12 return False
13 count[card + i] -= count[card]
14 return Trueℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(n) for storing the frequency counts.
- 1The total number of cards must be divisible by groupSize to form complete groups.
- 2Using a frequency map allows us to efficiently manage counts and check for consecutive numbers.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.