Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: Can a hand of cards be split into groups of exactly w consecutive values? Greedily start groups at the smallest remaining card.

Problem: Can a hand of cards be split into groups of exactly w consecutive values? Greedily start groups at the smallest remaining card.
from collections import Counter
def can_group(hand, w):
    if len(hand) % w: return False
    c = Counter(hand)
    for x in sorted(c):
        k = c[x]
        if k:
            for y in range(x, x + w):
                if c[y] < k: return False
                c[y] -= k
    return True
print(can_group([4, 5, 6, 5, 6, 7, 9, 10, 11], 3), can_group([1, 2, 3, 4, 5, 6], 4), can_group([5, 6, 7, 5, 6, 8], 3))
What is printed?
  1. A. True True False
  2. B. True False True
  3. C. True False False
  4. D. False False False

Correct answer: C. True False False

The smallest remaining card can only be the START of a group, so all k copies of it open k groups that need x+1 … x+w−1 as well. First hand: 4-5-6, 5-6-7, 9-10-11. Six cards cannot form groups of 4. [5, 6, 7, 5, 6, 8]: after 5-6-7, the remaining 5, 6, 8 are not consecutive. O(n log n).

More Coding Interview Problems questions

Exams that ask this topic