Hand Of Straights Problem
Description
LeetCode Problem 846.
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 i^th 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 <= 10^4
- 0 <= hand[i] <= 10^9
- 1 <= groupSize <= hand.length
Solution
Approach: Greedy from the Smallest Card
Look at the smallest card value x still in the hand. No group can contain x unless the group starts at x, because there is no smaller card to come before it. So every copy of x must start its own group x, x + 1, …, x + groupSize - 1. That choice is forced, so a greedy approach that always handles the smallest card first never makes a wrong decision.
- If
hand.lengthis not a multiple ofgroupSize, returnfalse. - Count how many times each value appears.
- Go through the distinct values in increasing order. For a value
startwithneed = count[start] > 0:- every value from
starttostart + groupSize - 1must have at leastneedcopies left, otherwise returnfalse; - subtract
needfrom each of them.
- every value from
- If every value is used up this way, return
true.
Handling all need copies of the smallest value at once, instead of building groups one at a time, means the inner loop runs once per distinct starting value rather than once per group.
When later values are reached, their counts may already be 0 because earlier groups used them; those are simply skipped.
Complexity: O(n log n) time for sorting the distinct values, and O(n) space for the counts, where n is the length of hand. The inner loops run O(n) times in total, since every group started uses need · groupSize cards.
import collections
class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
if len(hand) % groupSize != 0:
return False
count = collections.Counter(hand)
for start in sorted(count):
need = count[start] # the smallest card left must start this many groups
if need == 0:
continue
for value in range(start, start + groupSize):
if count[value] < need:
return False
count[value] -= need
return True