progress

~/problems / Range queries / Fenwick tree (BIT)

Deli counter: people ahead of you

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 min

A deli gives each party a ticket 1 .. n at opening and serves them in order. While they wait, people drift away, and a screen shows anyone how many people are still ahead of them.

Implement DeliLine(party_sizes) (ticket t starts with party_sizes[t - 1] people):

  • leave(t, k): k people from party t leave (1 <= k <= its current size; a party may become empty).
  • people_ahead(t) -> int: people still waiting in parties 1 .. t - 1.
line = DeliLine([2, 4, 1, 3])   # parties: #1=2, #2=4, #3=1, #4=3
line.people_ahead(4)            # 7    (2 + 4 + 1)
line.leave(2, 3)                # party #2 now has 1 person
line.people_ahead(4)            # 4
line.leave(1, 2)                # party #1 is empty
line.people_ahead(3)            # 1
line.people_ahead(1)            # 0    (nobody is ever ahead of ticket 1)

Up to 10**5 parties (sizes 1..20) and 10**5 calls.

⭐ Bonus: summing sizes[:t-1] on each call is O(n) and still passes; a speed test with 10**5 calls on 10**5 parties earns a star at O(log n) per call.

Show hint

a Fenwick tree over tickets holding current sizes: leave is add(t, -k), people_ahead(t) is prefix_sum(t - 1).

Topic: Fenwick tree (BIT). Point update + prefix sum in O(log n) with i & -i.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc