846. Hand of Straights
Problem Statement
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/
Intuition
Apprach:
We keep track of minimum element using minheap
And then from that minimum element try to find
Using loop that if val+k elements exist
Now, if freq of element goes to zero, we pop in heap
But if
1 -> 1
2-> 0
Now, 1 has freq, but we will need 2, so we return falseLinks
https://leetcode.com/problems/hand-of-straights/description/
Video Links
https://www.youtube.com/watch?v=amnrMCVd2YI&t=8s&ab_channel=NeetCode
Approach 1:
class Solution {
public:
bool isNStraightHand(vector<int>& hand, int size) {
if(hand.size() % size != 0)
return false;
unordered_map<int,int> mp;
priority_queue<int, vector<int>, greater<int>> pq;
for(auto &it: hand)
mp[it]++;
for(auto &it: mp)
pq.push(it.first);
while(!pq.empty()){
int val = pq.top();
for(int i=0; i<size; i++){
if(mp.find(val+i) == mp.end())
return false;
mp[val+i]--;
if(mp[val+i] == 0){
if(pq.top() != i+val)
return false;
pq.pop();
}
}
}
return true;
}
};Approach 2:
Approach 3:
Approach 4:
Similar Problems
Last updated