Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE
Problem: Find the inefficiency: two BFS versions on an R × C open grid. One marks a cell visited when it is pushed, the other only when it is popped. Count total pushes.
Problem: Find the inefficiency: two BFS versions on an R × C open grid. One marks a cell visited when it is pushed, the other only when it is popped. Count total pushes.
from collections import deque
D = ((1, 0), (0, 1), (-1, 0), (0, -1))
def bfs_early(R, C):
q = deque([(0, 0)]); seen = {(0, 0)}; pushes = 1
while q:
i, j = q.popleft()
for di, dj in D:
ni, nj = i + di, j + dj
if 0 <= ni < R and 0 <= nj < C and (ni, nj) not in seen:
seen.add((ni, nj)); q.append((ni, nj)); pushes += 1
return pushes
def bfs_late(R, C):
q = deque([(0, 0)]); seen = set(); pushes = 1
while q:
cell = q.popleft()
if cell in seen: continue
seen.add(cell); i, j = cell
for di, dj in D:
ni, nj = i + di, j + dj
if 0 <= ni < R and 0 <= nj < C and (ni, nj) not in seen:
q.append((ni, nj)); pushes += 1
return pushes
print(bfs_early(3, 3), bfs_late(3, 3), bfs_early(10, 10), bfs_late(10, 10))What is printed?- A. 9 13 100 400
- B. 13 9 181 100
- C. 9 9 100 100
- D. 9 13 100 181
Correct answer: D. 9 13 100 181
Marking on push guarantees each cell enters the queue exactly once (R·C pushes). Marking on pop lets a cell be pushed by several neighbours before it is processed – 13 pushes for 9 cells, 181 for 100 – still correct thanks to the 'if cell in seen: continue' guard, but the queue can grow to O(E) and, without that guard, cells would be expanded repeatedly. Both are O(R·C) here, but the early-mark version uses less memory and time.
More Coding Interview Problems questions
- Problem: Find the bug: binary search for the LAST x in [lo, hi] with ok(x) true (here the largest x with x² ≤ 30). The first version uses…
- Problem: n ≤ 2·10⁵ meetings [s, e); choose the maximum number of non-overlapping ones. Compare three greedy orders: by end time, by start…
- Problem: A road network has weights 1..5 (n, m ≤ 2·10⁵). A candidate solution runs plain BFS and sets dist[v] = dist[u] + w the first time…
- Problem: Each link succeeds with a probability; find the most reliable path from 0 to 3 (maximise the product). Dijkstra works with a…
- Problem: Board game on squares 1..n: roll a die (1–6); landing on the foot of a ladder or the head of a snake moves you to its other end…
- Problem: Find the bug: Kahn's algorithm is used to schedule build steps, but nobody checks whether a cycle exists. What does it return for…