Python 3D Academyবাংলা

Min stack and a hit counter

🌍 In real life. At a wedding in Old Dhaka the caterers keep the clean steel plates in one pile, and the plates come in different sizes: 25, 18 and 30 cm across. Plates go on and come off only at the top, yet the children keep asking for the smallest plate in the pile, and lifting every plate to check takes ages. Meanwhile an online clothes shop, busy with its Eid sale, shows "visits in the last 5 minutes" on its front page: every visit must count for exactly 300 seconds and then be forgotten.

The idea in one sentence: design the data so that each question is answered by looking in one place: a min stack writes, next to every item, the smallest item from the bottom up to it, and a hit counter keeps the hit times in a deque, oldest at the front, and drops the old ones from the front.

Its words:

  • min stack: a stack whose push, pop, top and get_min all take O(1) time
  • running minimum: the smallest item from the bottom of the stack up to this one
  • hit counter: counts the hits (visits) of the last 300 seconds: a hit at second h still counts at second t while t − h < 300
  • amortised O(1): one call may do a lot of work, but averaged over all the calls each one costs a fixed number of steps

The min stack, step by step:

  1. keep a list of pairs: (item, the running minimum up to it)
  2. push(x): the new pair's minimum is the smaller of x and the minimum stored on top (just x on an empty stack)
  3. pop(): remove the top pair and give back its item; the pair now on top already knows the minimum of what is left
  4. top() reads the top item and get_min() the top minimum: one look each

The tower shows the plates; the minimum stored with each one is written here. 25 is pushed with 25, 18 with 18, and 30 with 18; peeking with top() shows 30. When 30 and 18 come off, 25 is on top again and still carries 25; then 22 arrives with min(22, 25) = 22:

Why the stored minimum stays right. A stack changes only at the top. While a plate is in the pile, every plate below it stays put, so the smallest plate from the bottom up to it can't change: the number written when it was pushed is still true. When the top plate leaves, the plate below becomes the top, and its number is exactly the minimum of what is left. Nothing is ever recomputed. (A variant keeps a second stack of minimums only, pushed when x <= mins[-1]; it saves memory when the plates mostly get bigger.)

The hit counter, step by step:

  1. keep a deque of hit times, oldest at the front
  2. hit(t): append t at the back
  3. get_hits(t): while the front hit is 300 seconds old or more (q[0] <= t − 300), popleft it
  4. every hit that is left is from the last 300 seconds: return len(q)

The scene draws the deque as the ticket line of Lesson 40.1, one person per visit, and serving the person at the front means forgetting the oldest visit. Tania visits at second 10, Sabbir at 50 and Nila at 200. At second 320 the cut-off is 320 − 300 = 20, so Tania leaves the front: 2 visits. Rafi visits at 340. At 400 the cut-off is 100 and Sabbir leaves (2 visits); at 520 it is 220 and Nila leaves, so only Rafi's visit counts:

Why dropping from the front is right. Hits come in time order, so the deque is sorted, oldest at the front. If the front hit is less than 300 seconds old, every hit behind it is newer, so they all count. If it is 300 seconds old or more, it will never count again, because time only moves forward, so it can go for good. When the loop stops, every hit left counts, and len(q) is the answer.

What it costs, by counting. The min stack does one or two steps per call, however tall the pile: O(1) time per operation and O(n) memory, two numbers per plate. Recomputing min(stack) instead, on a pile of 100,000 plates for each of 100,000 get_min calls, means 100,000 × 100,000 = 10,000,000,000 comparisons. A site with 50 hits a second gets 50 × 86,400 = 4,320,000 hits a day. Each is appended once and dropped at most once, so the whole day costs at most 8,640,000 deque steps, plus one check per get_hits call to stop the loop. One call after a quiet night may drop thousands of hits, but each of those was paid for by its own hit: amortised O(1) time per call. Memory is O(the hits of the last 300 seconds), here at most 50 × 300 = 15,000 times. Another design keeps 300 buckets, one per second (t % 300): fixed memory however busy the site, but every get_hits adds up all 300.

class MinStack:
    def __init__(self):
        self.items = []                    # pairs: (x, the smallest from the bottom up to x)

    def push(self, x):
        smallest = min(x, self.items[-1][1]) if self.items else x
        self.items.append((x, smallest))

    def pop(self):
        return self.items.pop()[0]         # the pair below already knows its own minimum

    def top(self):
        return self.items[-1][0]

    def get_min(self):
        return self.items[-1][1]

from collections import deque

class HitCounter:
    def __init__(self):
        self.q = deque()                   # hit times, oldest at the front

    def hit(self, t):
        self.q.append(t)

    def get_hits(self, t):
        while self.q and self.q[0] <= t - 300:   # 300 seconds old or more: it never counts again
            self.q.popleft()
        return len(self.q)

plates = MinStack()
for size in [25, 18, 30]:
    plates.push(size)
print(plates.top(), plates.get_min())
plates.pop()
plates.pop()
print(plates.top(), plates.get_min())

counter = HitCounter()
for t in [10, 50, 200]:
    counter.hit(t)
print(counter.get_hits(320))
counter.hit(340)
print(counter.get_hits(400), counter.get_hits(520))

Mistakes and edge cases.

  • one variable for the minimum: it can't bring the old minimum back after a pop: once the 18 cm plate is gone, the smallest is the 25 cm one again
  • two stacks and equal minimums: in the variant, push onto the minimums when x <= mins[-1], not <; otherwise, with two 18 cm plates, popping one loses the other
  • an empty stack: top, pop and get_min on an empty stack raise IndexError, like [].pop(); check if self.items first when that can happen
  • exactly 300 seconds: at second 301 the hit from second 1 no longer counts, so drop while q[0] <= t − 300; and use while, not if, since a quiet spell can leave many old hits
  • hits in the same second: a set of times counts five hits at second 5 as one; the deque keeps them all, and if thousands come each second, store [t, count] pairs instead

Quiz

  1. What does this print?

    class MinStack:
        def __init__(self):
            self.items = []                    # pairs: (x, the smallest from the bottom up to x)
    
        def push(self, x):
            smallest = min(x, self.items[-1][1]) if self.items else x
            self.items.append((x, smallest))
    
        def pop(self):
            return self.items.pop()[0]         # the pair below already knows its own minimum
    
        def top(self):
            return self.items[-1][0]
    
        def get_min(self):
            return self.items[-1][1]
    
    s = MinStack()
    for x in [6, 3, 8, 3]:
        s.push(x)
    s.pop()
    s.pop()
    print(s.get_min(), s.top())
    s.pop()
    print(s.get_min())
  2. Each pair stores the minimum from when it was pushed and never updates it. Why is that safe?

    • The items below it can't change while it is on the stack
    • push always puts the smallest item on top
    • get_min sorts the stack before it answers
  3. What does this print?

    from collections import deque
    
    class HitCounter:
        def __init__(self):
            self.q = deque()                   # hit times, oldest at the front
    
        def hit(self, t):
            self.q.append(t)
    
        def get_hits(self, t):
            while self.q and self.q[0] <= t - 300:   # 300 seconds old or more: it never counts again
                self.q.popleft()
            return len(self.q)
    
    c = HitCounter()
    for t in [1, 2, 3, 300]:
        c.hit(t)
    print(c.get_hits(300), c.get_hits(301), c.get_hits(599), c.get_hits(600))
  4. Why does the hit counter keep its times in a deque rather than a list?

    • popleft is O(1), while a list's pop(0) moves every item behind the front
    • A deque keeps its items sorted by itself
    • A list can't hold the same time twice
  5. A site gets 1,000,000 hits in a day and get_hits is called 1,000,000 times. One call after a quiet night drops 5,000 hits at once. What is the total time?

    • O(hits + calls): each hit is appended once and dropped at most once
    • O(hits × calls): any call may scan the whole deque
    • O(300 × calls): each call looks at all 300 seconds
  6. After hits at seconds 1, 2 and 3, get_hits(1000) gives 2 instead of 0. Which line is wrong?

    from collections import deque
    
    class HitCounter:
        def __init__(self):
            self.q = deque()
    
        def hit(self, t):
            self.q.append(t)
    
        def get_hits(self, t):
            if self.q and self.q[0] <= t - 300:
                self.q.popleft()
            return len(self.q)

Coding tasks

  1. Write a class MinStack with push(x), pop() (removes the top item and returns it), top() (returns the top item) and get_min() (returns the smallest item in the stack), each in O(1) time. Every test makes a new MinStack, runs a list of calls on it and shows what each call returns (push returns None). The tests never call pop, top or get_min on an empty stack.

  2. Write a class HitCounter with hit(t), which records a hit at second t, and get_hits(t), which returns how many hits happened in the last 300 seconds, that is, at seconds h with t - h < 300. Times never go backwards, several hits may share a second, and each test runs a list of calls on a new counter and shows what each call returns (hit returns None).