iq.lab
Python starts when a code cell comes near or you run one
05 Stacks and queues

Checkpoint

Stacks and queues

Eleven items from all three lessons: stacks, monotonic stacks, and queues with deques. Every input is new, so work each one out on paper: write the stack or the deque down after every step, because that is where the classic mistakes show. The last two items are code; the rest take a few minutes each.

  1. Question 1 of 11.

    Four jobs from a data team. Which one needs a queue (first in, first out) rather than a stack?

  2. Question 2 of 11.

    This postfix evaluator handles only -. The expression is 9 4 - 3 -. Type exactly what the program prints.

    stack = []
    for token in ["9", "4", "-", "3", "-"]:
        if token == "-":
            a = stack.pop()
            b = stack.pop()
            stack.append(a - b)
        else:
            stack.append(int(token))
    print(stack[-1])
    
  3. Question 3 of 11.

    Run the stack version of next greater element (pop while the item on top is strictly smaller than the new item) on [2, 7, 3, 1, 5, 4, 8]. How many indexes are popped over the whole walk? Type a whole number.

    pops

    Type a number: 12, -1, 0.5 and 3/4 all work.

  4. Question 4 of 11.

    This loop keeps its work in a deque, but it takes items with pop(). Type exactly what it prints.

    from collections import deque
    
    children = {"a": ["b", "c"], "b": ["d"], "c": ["e"]}
    todo = deque(["a"])
    order = []
    while todo:
        node = todo.pop()
        order.append(node)
        for child in children.get(node, []):
            todo.append(child)
    print(order)
    
  5. Question 5 of 11.

    This bracket checker rejects a wrong closer and a closer with nothing open, but its last line is return True.

    def is_valid(s):
        partner = {")": "(", "]": "[", "}": "{"}
        stack = []
        for ch in s:
            if ch in "([{":
                stack.append(ch)
            elif not stack or stack[-1] != partner[ch]:
                return False
            else:
                stack.pop()
        return True

    Which input does it get wrong?

  6. Question 6 of 11.

    Bars of width 1 stand side by side with heights [4, 2, 3, 3, 1]. What is the area of the largest rectangle that fits under them? Type a whole number.

    area

    Type a number: 12, -1, 0.5 and 3/4 all work.

  7. Question 7 of 11.

    A queue built from two stacks has 1,000 items in in_stack and none in out_stack. The next pop moves all 1,000 of them. Which statement is true?

  8. Question 8 of 11.

    This min stack keeps a second stack, mins, and adds to it only when a value is a new minimum. A pop that removes the current minimum also pops mins. Type exactly what it prints.

    stack = []
    mins = []
    for val in [4, 2, 2, 7]:
        stack.append(val)
        if not mins or val < mins[-1]:
            mins.append(val)
    for _ in range(2):
        if stack.pop() == mins[-1]:
            mins.pop()
    print(stack, mins[-1])
    
  9. Question 9 of 11.

    This is the sliding window maximum from the lesson with one change: the front check uses < instead of <=. Type exactly what it prints.

    from collections import deque
    
    def max_sliding_window(nums, k):
        candidates = deque()
        out = []
        for i, x in enumerate(nums):
            while candidates and nums[candidates[-1]] <= x:
                candidates.pop()
            candidates.append(i)
            if candidates[0] < i - k:
                candidates.popleft()
            if i >= k - 1:
                out.append(nums[candidates[0]])
        return out
    
    print(max_sliding_window([5, 1, 2, 3], 2))
    
  10. Question 10 of 11.

    Run the tests before you submit. This question counts as correct if your latest run passes every check.

    Code itSimplify a folder path

    A Unix-style path names a folder, starting from the root folder /. Inside it, . means the current folder, .. means the parent folder (at the root, .. stays at the root), and several slashes in a row count as one. Every other piece is a folder name.

    Write simplify_path(path), which returns the shortest form of the same folder: a /, then the folder names joined by single slashes, with no ., no .. and no slash at the end. For example, "/data//raw/./2024/../2025/" gives "/data/raw/2025".

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.
  11. Question 11 of 11.

    Run the tests before you submit. This question counts as correct if your latest run passes every check.

    Code itThe nearest bigger item to the left

    Write previous_greater(nums). For each item, it returns the nearest item to its left that is strictly bigger, or -1 if there is none. For [3, 1, 2, 5, 4] the answer is [-1, 3, 3, -1, 5]: the 2's nearest bigger item on the left is the 3, because the 1 between them is smaller.

    Use one walk with a stack. The tests include 30,001 items, where scanning left from every item runs out of time.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.
0 of 11 answered. Unanswered questions count as wrong.