cswork / templatesOpen the Line 500 list

STOP 32 · DESIGN & BITS

Container and Iterator Design

Lazy iterator: hasNext does the advancing O(1) amortised per call

Contest ratings Rating 1454–Rating 1454· median Rating 1454(1 of 8 problems rated by zerotrac)

Open the Line 500 list · stop 32 · 8 problems
Learn first
Leads to
No later stop builds on it.
How often asked
asked by 4 companies · in 4 reportsAmazon 1, Applied Intuition 1, Chime 1, Oracle 1

Warm up with this one

LC 225Implement Stack using QueuesEasy
Stuck? Peek at the approach

Implement a stack using only queue operations and compare charging reordering costs to pushes versus pops.

Key points

  1. Put "skip empty rows and reach the next valid element" in hasNext and let next only read; calling hasNext repeatedly then has no side effects.
  2. Keep only positions (row and column) instead of copying every element into one big array in the constructor.
  3. For arbitrarily nested lists keep a stack of positions, one per level; in Python a generator with yield from is the natural fit.

Common pitfalls

  • With empty rows in the middle or at the end, looking only at the next row makes hasNext return a wrong true.
  • A next that doesn't call hasNext first reads out of bounds.
  • Modifying the container while iterating throws ConcurrentModificationException in Java and fails silently elsewhere.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Tree traversal · stack and queue

Walk the tree in preorder, inorder, postorder, level order

Try your own input
ABCDEFG
CurrentDiscovered / computedAnswer
Stack bottom → top, or queue front → back
Empty
Order
Preorder
Output
—

One tree, four traversal orders. #k under a node is its position in the current output.

InvariantThe three depth-first orders differ only in where the root is output: before, between or after its subtrees. Level order uses a queue, and first in, first out means level by level.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 225, with it.

Python
class Flatten2D:
    """Iterates a list of lists in order, skipping empty rows."""

    def __init__(self, rows: list[list[int]]):
        self.rows, self.r, self.c = rows, 0, 0

    def has_next(self) -> bool:
        while self.r < len(self.rows) and self.c == len(self.rows[self.r]):
            self.r, self.c = self.r + 1, 0  # skip finished and empty rows
        return self.r < len(self.rows)

    def next(self) -> int:
        if not self.has_next():
            raise StopIteration
        self.c += 1
        return self.rows[self.r][self.c - 1]
C++
// Iterates a vector of vectors in order, skipping empty rows.
class Flatten2D {
    vector<vector<int>> rows;  // own a copy: a temporary argument would dangle
    size_t r = 0, c = 0;

public:
    Flatten2D(vector<vector<int>> rows) : rows(std::move(rows)) {}

    bool hasNext() {
        while (r < rows.size() && c == rows[r].size()) r++, c = 0;  // skip finished and empty rows
        return r < rows.size();
    }

    int next() {
        if (!hasNext()) throw out_of_range("no more elements");
        return rows[r][c++];
    }
};
Java
// Iterates a list of lists in order, skipping empty rows.
class Flatten2D implements Iterator<Integer> {
    private final List<List<Integer>> rows;
    private int r = 0, c = 0;

    Flatten2D(List<List<Integer>> rows) {
        this.rows = rows;
    }

    @Override
    public boolean hasNext() {
        while (r < rows.size() && c == rows.get(r).size()) { // skip finished and empty rows
            r++;
            c = 0;
        }
        return r < rows.size();
    }

    @Override
    public Integer next() {
        if (!hasNext()) throw new NoSuchElementException();
        return rows.get(r).get(c++);
    }
}
Go
// Flatten2D iterates a slice of slices in order, skipping empty rows.
type Flatten2D struct {
	rows [][]int
	r, c int
}

func (it *Flatten2D) HasNext() bool {
	for it.r < len(it.rows) && it.c == len(it.rows[it.r]) {
		it.r, it.c = it.r+1, 0 // skip finished and empty rows
	}
	return it.r < len(it.rows)
}

func (it *Flatten2D) Next() int {
	if !it.HasNext() {
		panic("no more elements")
	}
	it.c++
	return it.rows[it.r][it.c-1]
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

A queue from two stacks: refill only when the out-stack is emptyO(1) amortised per operation · O(n) space

When only stacks are available (or a stack must stand in for another container): push new items onto inbox, take them from outbox, and pour all of inbox across only when outbox is empty, which reverses the order exactly. Each item moves at most once, so it is O(1) amortised. LC 232 (Implement Queue using Stacks); LC 225 goes the other way.

Python
class MyQueue:
    """A FIFO queue built from two stacks (LC 232)."""

    def __init__(self):
        self.inbox: list[int] = []  # new items go on top here
        self.outbox: list[int] = []  # items leave from here, oldest on top

    def push(self, x: int) -> None:
        self.inbox.append(x)

    def _refill(self) -> None:
        if not self.outbox:  # only when empty, or the order breaks
            while self.inbox:
                self.outbox.append(self.inbox.pop())

    def pop(self) -> int:
        self._refill()
        return self.outbox.pop()

    def peek(self) -> int:
        self._refill()
        return self.outbox[-1]

    def empty(self) -> bool:
        return not self.inbox and not self.outbox
C++
// A FIFO queue built from two stacks (LC 232).
class MyQueue {
    stack<int> inbox, outbox;  // new items go on inbox; items leave from outbox, oldest on top

    void refill() {
        if (outbox.empty())  // only when empty, or the order breaks
            for (; !inbox.empty(); inbox.pop()) outbox.push(inbox.top());
    }

public:
    void push(int x) { inbox.push(x); }
    int pop() {
        refill();
        int x = outbox.top();
        outbox.pop();
        return x;
    }
    int peek() {
        refill();
        return outbox.top();
    }
    bool empty() const { return inbox.empty() && outbox.empty(); }
};
Java
// A FIFO queue built from two stacks (LC 232).
class MyQueue {
    private final Deque<Integer> inbox = new ArrayDeque<>(); // new items go on top here
    private final Deque<Integer> outbox = new ArrayDeque<>(); // items leave from here, oldest on top

    void push(int x) {
        inbox.push(x);
    }

    int pop() {
        refill();
        return outbox.pop();
    }

    int peek() {
        refill();
        return outbox.peek();
    }

    boolean empty() {
        return inbox.isEmpty() && outbox.isEmpty();
    }

    private void refill() {
        if (outbox.isEmpty()) // only when empty, or the order breaks
            while (!inbox.isEmpty()) outbox.push(inbox.pop());
    }
}
Go
// MyQueue is a FIFO queue built from two stacks (LC 232).
type MyQueue struct {
	inbox, outbox []int // new items go on inbox; items leave from outbox, oldest on top
}

func (q *MyQueue) Push(x int) { q.inbox = append(q.inbox, x) }

func (q *MyQueue) refill() {
	if len(q.outbox) == 0 { // only when empty, or the order breaks
		for len(q.inbox) > 0 {
			q.outbox = append(q.outbox, q.inbox[len(q.inbox)-1])
			q.inbox = q.inbox[:len(q.inbox)-1]
		}
	}
}

func (q *MyQueue) Pop() int {
	q.refill()
	x := q.outbox[len(q.outbox)-1]
	q.outbox = q.outbox[:len(q.outbox)-1]
	return x
}

func (q *MyQueue) Peek() int {
	q.refill()
	return q.outbox[len(q.outbox)-1]
}

func (q *MyQueue) Empty() bool { return len(q.inbox) == 0 && len(q.outbox) == 0 }
Each entry remembers the minimum up to itO(1) per operation · O(n) space

To read the stack's minimum (or maximum) in O(1) at any time: push each value together with the minimum of it and everything below it, so that minimum leaves with it and nothing is recomputed. LC 155 (Min Stack); two such stacks give a queue an O(1) minimum as well.

Python
class MinStack:
    """A stack with O(1) get_min (LC 155)."""

    def __init__(self):
        self.items: list[tuple[int, int]] = []  # (value, minimum of it and everything below)

    def push(self, x: int) -> None:
        low = min(x, self.items[-1][1]) if self.items else x
        self.items.append((x, low))

    def pop(self) -> None:
        self.items.pop()

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

    def get_min(self) -> int:
        return self.items[-1][1]
C++
// A stack with O(1) getMin (LC 155).
class MinStack {
    vector<pair<int, int>> items;  // {value, minimum of it and everything below}

public:
    void push(int x) {
        int low = items.empty() ? x : min(x, items.back().second);
        items.push_back({x, low});
    }
    void pop() { items.pop_back(); }
    int top() const {
        return items.back().first;
    }
    int getMin() const {
        return items.back().second;
    }
};
Java
// A stack with O(1) getMin (LC 155).
class MinStack {
    private final Deque<int[]> items = new ArrayDeque<>(); // {value, minimum of it and everything below}

    void push(int x) {
        items.push(new int[] {x, items.isEmpty() ? x : Math.min(x, items.peek()[1])});
    }

    void pop() {
        items.pop();
    }

    int top() {
        return items.peek()[0];
    }

    int getMin() {
        return items.peek()[1];
    }
}
Go
// MinStack is a stack with O(1) GetMin (LC 155).
type MinStack struct {
	items [][2]int // {value, minimum of it and everything below}
}

func (s *MinStack) Push(x int) {
	low := x
	if n := len(s.items); n > 0 {
		low = min(x, s.items[n-1][1])
	}
	s.items = append(s.items, [2]int{x, low})
}

func (s *MinStack) Pop()        { s.items = s.items[:len(s.items)-1] }
func (s *MinStack) Top() int    { return s.items[len(s.items)-1][0] }
func (s *MinStack) GetMin() int { return s.items[len(s.items)-1][1] }

Why it works

  1. Invariant: after hasNext returns, (r, c) points at the next valid element or r has passed the last row; next only reads and steps once, and the following hasNext restores the invariant.
  2. Idempotence: hasNext only skips finished or empty rows and changes nothing when already on a valid element, so repeated calls give the same answer.
  3. Amortised O(1): every row is skipped at most once and every element is read once, so total work is rows plus elements.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
迭代器设计我把跳过空行、走到下一个有效元素放在 hasNext 里,next 只负责读取当前元素并前进一格,开头先调用一次 hasNext 防止越界。这样 hasNext 连续调用多次也没有副作用。我只保存行号和列号,不在构造函数里把所有元素拷贝成一个大数组。每行最多被跳过一次,所以每次调用均摊 O(1)。
English
For iterator design I put skipping empty rows and reaching the next valid element in hasNext, while next only reads the current element and steps forward, calling hasNext first to stay in bounds. That way calling hasNext repeatedly has no side effects. I keep only a row and column index instead of copying everything into one big array in the constructor. Each row is skipped at most once, so every call is amortised O(1).

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

3 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

3 questions
  1. A stack with push, pop, top and O(1) getMin is usually built how?
  2. Why use collections.deque instead of a list with pop(0) for a BFS queue in Python?
  3. Starting empty, any n push and pop calls run. What does each operation cost?
    class Queue:
        def __init__(self):
            self.inbox, self.outbox = [], []
    
        def push(self, x):
            self.inbox.append(x)
    
        def pop(self):
            if not self.outbox:
                while self.inbox:
                    self.outbox.append(self.inbox.pop())
            return self.outbox.pop()

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

class Flatten2D:

Practice by stage

This stop's 8 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Foundation 2

#ProblemApproachRating
225Implement Stack using QueuesImplement a stack using only queue operations and compare charging reordering costs to pushes versus pops.
232Implement Queue using StacksImplement a queue with two stacks and explain amortized O(1) operations, ensuring peek preserves logical order.

Core 6

#ProblemApproachRating
155Min StackMaintain the current minimum in sync with the stack and test repeated minima and consecutive pops.
622Design Circular QueueDesign a circular buffer with clear invariants for full, empty, and index wraparound.
641Design Circular DequeExtend the buffer to insertion and deletion at both ends, systematically testing all four boundary operations and capacity one.
707Design Linked ListImplement indexed access, insertion, and deletion, using sentinels to unify head, tail, and empty-list behavior.
173Binary Search Tree IteratorPerform inorder traversal lazily with a stack and explain iterator state and amortized complexity.
1472Design Browser HistoryDesign a browsing-history cursor, truncate forward history on a new visit, and handle backward and forward requests beyond the boundaries.Rating 1454