CodeArchon

mediumGreedyGoogle

Card Flush Builder

A card player checks if their hand can be grouped into runs of consecutive values of a fixed length.

Given a hand and a group size k, return true iff the hand can be partitioned into groups of k consecutive integers.

Choose approach

1
0
2
1
3
2
6
3
2
4
3
5
4
6
7
7
8
8
Mapcount
1→0
2→1
3→1
4→1
6→1
7→1
8→1
1/4
Narrationstep 1 of 4

Formed 1 straights starting at 1.

1from collections import Counter
2def isNStraightHand(hand, k):
3 if len(hand) % k: return False
4 count = Counter(hand)
5 for start in sorted(count):
6 c = count[start]
7 if c == 0: continue
8 for i in range(k):
9 if count[start + i] < c: return False
10 count[start + i] -= c
11 return True
Variables
start=1
c=1

How to think about it

  1. n % k != 0 is an immediate 'false'.
  2. Smallest value must start exactly count[smallest] groups.

Edge cases to catch in interview

  • Empty hand -> true.
  • k = 1 -> always true.

Examples

Example 1false
{"hand":[1,2,3,4,5],"groupSize":4,"values":[1,2,3,4,5]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed