846. Hand of Straights
Explanation:
To solve this problem, we can use a hashmap to count the frequency of each card value in the hand. Then, we can iterate over the keys of the hashmap in sorted order. For each card value, we check if there are enough cards available to form a group of size groupSize
. If so, we decrement the count of the current card value and the counts of the consecutive cards in the group. If at any point we find that we cannot form a group, we return false. If we are able to form groups for all card values, we return true.
Algorithm:
- Create a hashmap to store the frequency of each card value in the hand.
- Sort the keys of the hashmap.
- For each card value in sorted order:
- If the count of the current card value is greater than 0:
- Decrement the count of the current card value.
- Decrement the counts of the consecutive cards in the group.
- If we cannot form a group, return false.
- If the count of the current card value is greater than 0:
- If we are able to form groups for all card values, return true.
Time Complexity: O(n log n) where n is the number of cards in the hand.
Space Complexity: O(n) where n is the number of cards in the hand.
:
class Solution {
public boolean isNStraightHand(int[] hand, int groupSize) {
if (hand.length % groupSize != 0) {
return false;
}
TreeMap<Integer, Integer> countMap = new TreeMap<>();
for (int card : hand) {
countMap.put(card, countMap.getOrDefault(card, 0) + 1);
}
for (int card : countMap.keySet()) {
int count = countMap.get(card);
if (count > 0) {
for (int i = 0; i < groupSize; i++) {
if (countMap.getOrDefault(card + i, 0) < count) {
return false;
}
countMap.put(card + i, countMap.get(card + i) - count);
}
}
}
return true;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.