QueueMedium

Generate Numbers Visualizer

What is Generate Numbers

Generate the first n positive integers that use only the digits 1 and 2, in increasing order.

Approach

Treat the queue like a breadth-first walk of the digit choices. Each number produces two children.

Visualization & algorithm

The queue growing by appending 1 and 2
queue = [1, 2]
while we need more numbers:
x = dequeue
enqueue x with a 1 appended
enqueue x with a 2 appended
the first n dequeued values are the answer
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.

Complexity

PieceCostWhy
TimeO(n)Each of the n numbers is enqueued once.
SpaceO(n)The queue holds the numbers not yet printed.

Implementation

from collections import deque
def solve(self, n):
    q = deque(['1', '2'])
    out = []
    while len(out) < n:
        x = q.popleft()
        out.append(int(x))
        q.append(x + '1')
        q.append(x + '2')
    return out