What is Generate Numbers
Generate the first n positive integers that use only the digits 1 and 2, in increasing order.
Approach
Visualization & algorithm
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
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each of the n numbers is enqueued once. |
| Space | O(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