Skip to content

Commit 8db1119

Browse files
committed
Sync LeetCode submission Runtime - 157 ms (75.82%), Memory - 18.5 MB (16.56%)
1 parent 0cdd3b3 commit 8db1119

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

0876-hand-of-straights/README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<p>Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size <code>groupSize</code>, and consists of <code>groupSize</code> consecutive cards.</p>
2+
3+
<p>Given an integer array <code>hand</code> where <code>hand[i]</code> is the value written on the <code>i<sup>th</sup></code> card and an integer <code>groupSize</code>, return <code>true</code> if she can rearrange the cards, or <code>false</code> otherwise.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> hand = [1,2,3,6,2,3,4,7,8], groupSize = 3
10+
<strong>Output:</strong> true
11+
<strong>Explanation:</strong> Alice&#39;s hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> hand = [1,2,3,4,5], groupSize = 4
18+
<strong>Output:</strong> false
19+
<strong>Explanation:</strong> Alice&#39;s hand can not be rearranged into groups of 4.
20+
21+
</pre>
22+
23+
<p>&nbsp;</p>
24+
<p><strong>Constraints:</strong></p>
25+
26+
<ul>
27+
<li><code>1 &lt;= hand.length &lt;= 10<sup>4</sup></code></li>
28+
<li><code>0 &lt;= hand[i] &lt;= 10<sup>9</sup></code></li>
29+
<li><code>1 &lt;= groupSize &lt;= hand.length</code></li>
30+
</ul>
31+
32+
<p>&nbsp;</p>
33+
<p><strong>Note:</strong> This question is the same as 1296: <a href="https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/" target="_blank">https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/</a></p>

0876-hand-of-straights/solution.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Approach 1: Using Map
2+
3+
from collections import Counter
4+
import heapq
5+
6+
class Solution:
7+
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
8+
hand_size = len(hand)
9+
10+
if hand_size % groupSize != 0:
11+
return False
12+
13+
card_count = Counter(hand)
14+
15+
# Min-heap to process the cards in sorted order
16+
min_heap = list(card_count.keys())
17+
heapq.heapify(min_heap)
18+
19+
while min_heap:
20+
current_card = min_heap[0] # Get smallest card
21+
22+
for i in range(groupSize):
23+
if card_count[current_card + i] == 0:
24+
return False
25+
card_count[current_card + i] -= 1
26+
if card_count[current_card + i] == 0:
27+
if current_card + i != heapq.heappop(min_heap):
28+
return False
29+
30+
return True

0 commit comments

Comments
 (0)