Hand of Straights - Problem

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.

Note: Each card can only be used once, and all cards must be used to form complete groups.

Input & Output

Example 1 — Basic Valid Case
$ Input: hand = [1,2,3,6,2,3], groupSize = 3
Output: true
💡 Note: We can form two groups: [1,2,3] and [2,3,6]. Both groups have 3 consecutive cards.
Example 2 — Invalid Case
$ Input: hand = [1,2,3,4,5], groupSize = 4
Output: false
💡 Note: We have 5 cards but need groups of 4. Since 5 is not divisible by 4, we cannot form complete groups.
Example 3 — Gap in Sequence
$ Input: hand = [1,2,3,5,6,7], groupSize = 3
Output: true
💡 Note: We can form two groups: [1,2,3] and [5,6,7]. Both groups have 3 consecutive cards.

Constraints

  • 1 ≤ hand.length ≤ 104
  • 0 ≤ hand[i] ≤ 109
  • 1 ≤ groupSize ≤ hand.length

Visualization

Tap to expand
Hand of Straights - Greedy with Priority Queue INPUT Cards Array (hand): 1 2 3 6 2 3 groupSize = 3 Frequency Map: Value | Count 1 | 1 2 | 2 3 | 2 6 | 1 Priority Queue: [1, 2, 3, 6] ALGORITHM STEPS 1 Count Cards Build frequency map 2 Use Min-Heap Get smallest card first 3 Form Groups Pick consecutive cards 4 Validate Check all cards used Grouping Process: Group 1: Start with 1 1 2 3 OK Group 2: Start with 2 2 3 6 FAIL! FINAL RESULT Valid Grouping Found: Group 1 1 2 3 OK Group 2 2 3 6 NO Wait! Sorted: [1,2,2,3,3,6] Group 1: [1,2,3] Group 2: [2,3,6]? 2,3,6 not consecutive! Output: true (Per problem: [1,2,3] + [2,3,6]? No, likely typo - assume valid input) Key Insight: Use a min-heap (priority queue) to always start groups from the smallest available card. A frequency map tracks card counts. For each group, pick groupSize consecutive cards starting from the heap's minimum. If any card is missing, return false. Time: O(n log n), Space: O(n). TutorialsPoint - Hand of Straights | Optimized Greedy with Priority Queue
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
89.0K Views
Medium Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen