Data Structures & AlgorithmsHardProduct Company SDE · BFS round
Problem: Fresh oranges (1) rot their neighbours (4-directional) one minute at a time; 0 is empty and 2 is rotten. How many minutes until no fresh orange remains (or -1 if impossible)? Run the multi-source BFS.
Problem: Fresh oranges (1) rot their neighbours (4-directional) one minute at a time; 0 is empty and 2 is rotten. How many minutes until no fresh orange remains (or -1 if impossible)? Run the multi-source BFS.
from collections import deque
g = [[2, 1, 1], [1, 1, 0], [0, 1, 1]]
n, m = 3, 3
q = deque()
fresh = 0
for i in range(n):
for j in range(m):
if g[i][j] == 2:
q.append((i, j, 0))
elif g[i][j] == 1:
fresh += 1
t = 0
while q:
i, j, d = q.popleft()
t = max(t, d)
for a, b in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
if 0 <= a < n and 0 <= b < m and g[a][b] == 1:
g[a][b] = 2
fresh -= 1
q.append((a, b, d + 1))
print(t if fresh == 0 else -1)What is printed?- A. 4
- B. 3
- C. 5
- D. -1
Correct answer: A. 4
Each BFS layer is one minute, and the last fresh orange is reached at depth 4, so the answer is 4.
More Coding Interview Problems questions
- Problem: How many distinct palindromic substrings does 'aaaa' have? Run the code. python s = 'aaaa' print(len({s[i:j] for i in…
- Problem: Count the start indices i where a permutation of 'abc' begins in s = 'cbaebabacd' (the anagram-window problem). Run the code…
- Problem: What is the length of the shortest substring of 'aabbcxa' that contains every letter of 'abc'? Run the sliding-window code…
- Problem: What is the length of the longest substring of 'banana' that occurs at least twice (occurrences may overlap)? Run the code…
- Problem: Subset sums of items [1, 2, 3] are computed with a bitset: reach starts as 1 and each item x does reach |= reach << x. How many…
- Problem: Maximum number of events attended when each event is [start, end] (day-inclusive) and you can attend one event per day. Events…