Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: People queue at a single counter; person i wants t[i] tickets, buys one per second and, if still needing more, goes to the back. How many seconds until person k finishes? A closed-form count avoids simulation.

Problem: People queue at a single counter; person i wants t[i] tickets, buys one per second and, if still needing more, goes to the back. How many seconds until person k finishes? A closed-form count avoids simulation.
def time_for(t, k):
    return sum(min(x, t[k]) if i <= k else min(x, t[k] - 1) for i, x in enumerate(t))
print(time_for([3, 1, 4, 2], 2), time_for([3, 1, 4, 2], 0))
What is printed?
  1. A. 10 8
  2. B. 10 3
  3. C. 10 7
  4. D. 9 8

Correct answer: A. 10 8

Until person k buys their last ticket, everyone at or before k in line buys up to t[k] tickets, and everyone behind k buys up to t[k] − 1 (k finishes before their t[k]-th turn). k = 2 (needs 4): 3 + 1 + 4 + min(2, 3) = 10. k = 0 (needs 3): 3 + min(1, 2) + min(4, 2) + min(2, 2) = 8. A deque simulation gives the same 10 and 8 but costs O(sum of t).

More Coding Interview Problems questions

Exams that ask this topic