846. Hand of Straights #190
-
Topics: 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 Given an integer array Example 1:
Example 2:
Example 3:
Constraints:
Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/ |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The goal is to determine whether the array Approach:
Let's implement this solution in PHP: 846. Hand of Straights <?php
/**
* @param Integer[] $hand
* @param Integer $groupSize
* @return Boolean
*/
function isNStraightHand($hand, $groupSize) {
$n = count($hand);
// Early return if the number of cards is not divisible by groupSize
if ($n % $groupSize != 0) {
return false;
}
// Step 1: Count frequency of each card using a hash table
$count = [];
foreach ($hand as $card) {
if (isset($count[$card])) {
$count[$card]++;
} else {
$count[$card] = 1;
}
}
// Step 2: Sort the hand to ensure we start from the smallest card
sort($hand);
// Step 3: Try to form groups starting from the smallest card
foreach ($hand as $card) {
// If this card has already been used up, skip it
if ($count[$card] == 0) {
continue;
}
// Try to form a group of consecutive cards
for ($i = 0; $i < $groupSize; $i++) {
$currentCard = $card + $i;
// If the card is missing or insufficient in number, return false
if (!isset($count[$currentCard]) || $count[$currentCard] == 0) {
return false;
}
// Decrease the count of the current card
$count[$currentCard]--;
}
}
// If we successfully formed all the groups, return true
return true;
}
// Example 1
$hand1 = [1,2,3,6,2,3,4,7,8];
$groupSize1 = 3;
echo isNStraightHand($hand1, $groupSize1) ? 'true' : 'false'; // Output: true
// Example 2
$hand2 = [1,2,3,4,5];
$groupSize2 = 4;
echo isNStraightHand($hand2, $groupSize2) ? 'true' : 'false'; // Output: false
// Example 3
$hand3 = [2,1];
$groupSize3 = 2;
echo isNStraightHand($hand3, $groupSize3) ? 'true' : 'false'; // Output: true
?> Explanation:
Time Complexity:
Output:For
For
For
This solution efficiently checks if the hand can be rearranged into consecutive groups. |
Beta Was this translation helpful? Give feedback.
The goal is to determine whether the array
hand
can be rearranged into groups of consecutive cards where each group has a size ofgroupSize
.Approach:
Key Idea:
false
.Frequency Count:
Greedy Strategy: