oneby7

Greedy The best choice now

495. Hand of Straights

Medium

You are given an array of integers hand, where each number is the value written on one card, and an integer groupSize. Return true if you can split all the cards into groups so that every group holds exactly groupSize cards with consecutive values, and false otherwise.

Consecutive values means each value in a group is one more than the one before it, such as 6, 7, 8. Every card goes into exactly one group, and the order of the cards in hand does not matter.

Example 1

Input: hand = [4, 2, 7, 3, 5, 6, 3, 4, 5], groupSize = 3

Output: true

Explanation: The cards split into the groups 2, 3, 4, then 3, 4, 5, then 5, 6, 7. The two 3s, the two 4s and the two 5s each go into different groups.

Example 2

Input: hand = [5, 6, 6, 7, 8, 9], groupSize = 3

Output: false

Explanation: Nothing comes before the 5, so its group must be 5, 6, 7. The cards left are 6, 8 and 9, which are not consecutive.

Example 3

Input: hand = [3, 0, 1, 4, 2], groupSize = 2

Output: false

Explanation: The values 0 to 4 are consecutive, but five cards cannot form groups of 2. One card is always left over.

Check your understanding

Work out the answer for this input before you write any code.

hand = [1, 1, 2, 2, 3, 3], groupSize = 3

Constraints

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

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.