Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Problem: Dijkstra with a lazy binary heap: outdated heap entries are skipped when popped. Report the distance to node 4 and how many stale entries were skipped.
Problem: Dijkstra with a lazy binary heap: outdated heap entries are skipped when popped. Report the distance to node 4 and how many stale entries were skipped.
import heapq
def run(n, edges, s):
g = [[] for _ in range(n)]
for u, v, w in edges: g[u].append((v, w))
dist = [float('inf')] * n; dist[s] = 0
h, stale = [(0, s)], 0
while h:
d, u = heapq.heappop(h)
if d > dist[u]:
stale += 1; continue
for v, w in g[u]:
if d + w < dist[v]:
dist[v] = d + w; heapq.heappush(h, (dist[v], v))
return dist[4], stale
print(*run(5, [(0,1,4),(0,2,1),(2,1,2),(1,3,1),(2,3,5),(3,4,3)], 0))What is printed?- A. 7 0
- B. 8 2
- C. 7 1
- D. 7 2
Correct answer: D. 7 2
Popping 0 pushes (4,1) and (1,2); popping 2 improves 1 to 3 and pushes (6,3); popping 1 improves 3 to 4. The old entries (4,1) and (6,3) are both popped later and skipped, so stale = 2, and dist[4] = 4 + 3 = 7 via 0→2→1→3→4.
More Coding Interview Problems questions
- Problem: Longest increasing subsequence in O(n log n) with a 'tails' array (tails[i] = smallest possible tail of an increasing subsequence…
- Problem: Return the length of the shortest string that contains both a and b as subsequences. python def scs(a, b): m, n = len(a), len(b)…
- Problem: The reflected binary Gray code of i is i ^ (i >> 1). At which position of the 3-bit Gray sequence does the code 6 (110) appear?…
- Problem: A permissions engine isolates bits of a mask. python x = 88 print(x & -x, x & (x - 1)) What is printed?
- Problem: Rearrange the digits of a version list into the next lexicographically greater permutation. python def nxt(a): i = len(a) - 2…
- An analytics service holds a static array of n = 10⁵ integers and must answer q = 10⁶ queries 'minimum of a[l..r]' as fast as possible…