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?- A. True True False
- B. True False True
- C. True False False
- 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
- Problem: Swap at most two digits of a number once to obtain the maximum value. Record the last position of each digit and, scanning left…
- Problem: Flower i blooms on day bloom[i]. A bouquet needs k ADJACENT bloomed flowers, each flower used once. Find the minimum day by which…
- Problem: A number is 'magical' if it is divisible by a or b. Find the n-th magical number by binary search with inclusion–exclusion…
- Problem: Find the maximum difference between successive values in the SORTED order of an array, in linear time, using buckets (pigeonhole…
- Problem: Camera clips (start, end) cover parts of an event lasting T = 10 minutes; clips may be trimmed. Find the minimum number of clips…
- Problem: A broken calculator shows start and supports only 'double' and 'decrement by 1'. Find the minimum operations to reach target…