Data Structures & AlgorithmsModerateTCS NQT · BFS warm-up
Problem: How many cells of a 3 x 3 grid are at exactly 2 steps (4-directional moves, no obstacles) from the top-left cell? Run the BFS below.
Problem: How many cells of a 3 x 3 grid are at exactly 2 steps (4-directional moves, no obstacles) from the top-left cell? Run the BFS below.
from collections import deque
def cnt(n, m, s, k):
d = {s: 0}
q = deque([s])
while q:
x, y = q.popleft()
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nx, ny = x + dx, y + dy
if 0 <= nx < n and 0 <= ny < m and (nx, ny) not in d:
d[(nx, ny)] = d[(x, y)] + 1
q.append((nx, ny))
return sum(1 for v in d.values() if v == k)
print(cnt(3, 3, (0, 0), 2))What is printed?- A. 2
- B. 3
- C. 4
- D. 5
Correct answer: B. 3
Cells at Manhattan distance 2 from (0,0) are (2,0), (1,1) and (0,2). Diagonal moves would add cells and change the answer.
More Coding Interview Problems questions
- Problem: How many ordered pairs (a, b) with 1 <= a, b <= 6 have gcd(a, b) = 1? python from math import gcd print(sum(1 for a in range(1…
- Problem: What does the following print? python print(sum(bin(i).count('1') for i in range(1, 16)))
- Array a = [5, -3, 2, 4, -6, 1, 3, -2]. How many non-empty contiguous subarrays have a sum in the closed range [0, 4]?
- For the string s = "aabbabbaab", find the length of the longest substring with exactly as many letter a as letter b.
- For the array a = [4, 1, 7, 2, 2, 5, 3, 6], how many contiguous non-empty subarrays have XOR equal to 0? Use prefix XOR values.
- Array a = [3, 1, 4, 1, 5, 9, 2, 6]. How many subarrays of length exactly 3 have an even sum?