876. Hand Of Straights¶
Difficulty: Medium
LeetCode Problem View on GitHub
876. Hand of Straights
Medium
Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards.
Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.
Example 1:
Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3 Output: true Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]
Example 2:
Input: hand = [1,2,3,4,5], groupSize = 4 Output: false Explanation: Alice's hand can not be rearranged into groups of 4.
Constraints:
1 <= hand.length <= 1040 <= hand[i] <= 1091 <= groupSize <= hand.length
Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
Solution¶
class Solution {
public boolean isNStraightHand(int[] arr, int k) {
int n = arr.length;
if (n % k != 0)
return false;
HashMap<Integer, Integer> map = new HashMap<>();
TreeSet<Integer> set = new TreeSet<>();
for (int ele : arr) {
set.add(ele);
map.put(ele, map.getOrDefault(ele, 0) + 1);
}
while (map.size() > 0) {
int current = set.first();
for (int i = 0; i < k; i++) {
if (!map.containsKey(current)) return false;
else {
map.put(current, map.getOrDefault(current, 0) -1);
if (map.getOrDefault(current, 0) == 0) {
map.remove(current);
set.remove(current);
}
current += 1;
}
}
}
return true;
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here