Skip to main content
medium

Snack Bin Iterator — Flatten Nested Lists

Also known as: Flatten Nested List Iterator

Each basket is a list of snack numbers or more baskets, nested to any depth. Return every snack number in one flat list, left to right. Example: [[1, 1], 2, [1, 1]] => [1, 1, 2, 1, 1] Example: [[], [[[]]], 5] => [5]

This one is all about maintaining a clear stack meaning as you process input. Interviewers love it because it reveals your stack invariants and your edge-case discipline. Keep the stack invariant explicit; if it breaks, everything downstream breaks too.

Examples

You write

collect_snacks(bins: SnackInput)

  1. Example 1

    Input
    [[1,1],2,[1,1]]
    returns
    [1, 1, 2, 1, 1]
  2. Example 2

    Input
    [1,[4,[6]]]
    returns
    [1, 4, 6]

The pattern behind it

Design

I reach for it when

  • The statement describes a class with methods, not one function.
  • Each method needs to be fast, and the structure decides how fast.

Say this before you type. Say each method, the cost you want from it, and the structure that earns that cost.

All 27 Design problems

Stack

I reach for it when

  • Things must close in the reverse order they opened.
  • You need the nearest earlier or later item that is bigger or smaller.

Say this before you type. Say what each item on the stack is waiting for, and what lets you pop it.

All 17 Stack problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Flatten the Snack Binseasy
2Part 2
3Part 3

Each locked part opens in the editor once the part before it passes.