Leetcode 846. Hand of Straights
You are given an integer array hand
of size N
where hand[i]
represents the rank of the ith card. You are also given an integer groupSize
which represents the size of each group you want to divide the cards into.
You need to determine if it is possible to rearrange the cards in such a way that they can be grouped into sets of groupSize
with consecutive cards. If it is possible, return true
, otherwise return false
.
Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3
Output: true
Explanation: Possible to reorder into groups: [1,2,3], [2,3,4], [6,7,8]
Input: hand = [1,2,3,4,5], groupSize = 4
Output: false
Explanation: Cannot form groups of 4 with consecutive cards.
hand
: Are there any constraints on the possible values of the cards?
hand
is not constrained but will contain a reasonably large set of numbers.N % groupSize != 0
, it is immediately impossible to form the required groups.false
.#include <vector>
#include <map>
#include <algorithm>
bool isNStraightHand(std::vector<int>& hand, int groupSize) {
if (hand.size() % groupSize != 0)
return false;
std::map<int, int> frequency;
for (int card : hand) {
frequency[card]++;
}
for (const auto& entry : frequency) {
int startCard = entry.first;
int count = entry.second;
if (count > 0) {
for (int i = 1; i < groupSize; ++i) {
if (frequency[startCard + i] < count)
return false;
frequency[startCard + i] -= count;
}
}
}
return true;
}
groupSize
, this can be considered O(N).This solution ensures we efficiently determine if the hand can be rearranged into groups of the specified size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?