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?- A. 3
- B. 5
- C. 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
- Problem: How many binary strings of length 4 avoid the substring '11'? Run the code. python print(sum(1 for t in range(16) if '11' not in…
- Problem: What is the minimum number of insertions and deletions needed to turn 'abc' into 'adc'? (Only insertions and deletions are…
- Problem: What is the longest common prefix of the list ['flower', 'flow', 'flight']? Run the code. python import os…
- Problem: What does the following print? python print(' '.join('the sky is blue'.split()[::-1]))
- Problem: Which statement about Hall's theorem for a bipartite graph with sides L and R is correct?
- Problem: Which claim about the complexity of deciding 2-SAT (satisfiability of clauses with at most two literals) is correct?