581. Straight Hands

A board-game club has just dealt out a pile of ranked cards, where hand[i] is the rank printed on the i-th card. For the next round the host must split every card into teams of exactly groupSize cards, and the ranks inside one team must be consecutive integers, such as 9, 10, 11 (order inside a team does not matter). Each card belongs to exactly one team, and duplicate ranks are allowed as long as they land in different teams.

Return true if the whole pile can be split this way and false otherwise. The intended solution runs in O(n log n) time and O(n) extra space.

Example 1

Input:
hand = [8,6,7,7,9,8], groupSize = 3
Output:
true
Explanation:

The cards split into the teams 6-7-8 and 7-8-9, each made of three consecutive ranks.

Example 2

Input:
hand = [4,4,5,6], groupSize = 2
Output:
false
Explanation:

The two 4s must start different teams, giving 4-5 and 4-6, but 4 and 6 are not consecutive, so the answer is false.

Example 3

Input:
hand = [3,1,2,2,3,4,5,4], groupSize = 4
Output:
true
Explanation:

Teams 1-2-3-4 and 2-3-4-5 use all eight cards.

Constraints

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

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…