progress

~/problems / Backtracking

All strings of 0s and 1s

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

easy basics ~10 min

Write binary_strings(n: int) -> list[str] that returns every string of length n made of the characters "0" and "1". There are 2^n of them. They can come back in any order (the tests sort them).

binary_strings(2)   # ["00", "01", "10", "11"]
binary_strings(1)   # ["0", "1"]
binary_strings(0)   # [""]   one string of length 0
  • 0 <= n <= 12.
  • Write the recursion yourself; don't use itertools or count from 0 to 2^n - 1 in binary.
Show hint

build(path) makes one choice per position. If path has n characters, record it. Otherwise append "0" (choose), call build (explore), pop it (un-choose), then do the same with "1".

Topic: Recursion and backtracking. Choose, recurse, un-choose: subsets, permutations, N-queens, pruning.

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