Data Structures & AlgorithmsModerateCodeforces Div2 C · BFS on states

Problem: What is the minimum number of operations to go from 1 to 10 when each operation is +1 or 2? Run the BFS.

Problem: What is the minimum number of operations to go from 1 to 10 when each operation is +1 or *2? Run the BFS.
from collections import deque
d = {1: 0}
q = deque([1])
while q:
    x = q.popleft()
    for y in (x + 1, x * 2):
        if y <= 20 and y not in d:
            d[y] = d[x] + 1
            q.append(y)
print(d[10])
What is printed?
  1. A. 3
  2. B. 5
  3. C. 4
  4. D. 6

Correct answer: C. 4

The path 1 -> 2 -> 4 -> 5 -> 10 uses four operations, and no three-operation sequence reaches 10. BFS finds the shortest one.

More Coding Interview Problems questions

Exams that ask this topic