← Back to Backtracking

Generate All Binary Strings

2 of 6

Exercise 1: Generate All Binary Strings 🧩

Your Task

Write a function binary_strings(n) that returns all binary strings of length n.

A binary string only uses the characters '0' and '1'. Return the strings in any order.


Examples

print(binary_strings(1)) # Output: ['0', '1'] print(binary_strings(2)) # Output: ['00', '01', '10', '11'] print(binary_strings(3)) # Output: ['000', '001', '010', '011', '100', '101', '110', '111']

The Pattern

At each position you make one choice: place a '0' or a '1'.

              ""
            /    \
          "0"    "1"
          / \    / \
       "00" "01" "10" "11"

When the string reaches length n, add it to the result.


Starter Code

def binary_strings(n): # Your code here pass # Test your function: print(binary_strings(1)) # Expected: ['0', '1'] print(binary_strings(2)) # Expected: ['00', '01', '10', '11'] print(binary_strings(3)) # Expected: ['000', '001', '010', '011', '100', '101', '110', '111']

Hints

Try it yourself

Code: Generate All Binary Strings

Loading Python runtime…
Python …
Loading...
bash
$ Click "Run" to execute your code...