Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: A city grid has V = 10⁵ junctions; every road takes either 0 minutes (flyover) or 1 minute. What is the most efficient way to get shortest times from one source?
- A. Plain BFS with a queue – O(V + E) and exact
- B. 0-1 BFS with a deque: push 0-weight neighbours to the front, 1-weight to the back – O(V + E)
- C. Floyd–Warshall – O(V³)
- D. DFS that keeps the first distance found
Correct answer: B. 0-1 BFS with a deque: push 0-weight neighbours to the front, 1-weight to the back – O(V + E)
With only 0/1 weights the deque stays sorted by distance, so it behaves like Dijkstra without the log factor. Plain BFS counts edges and would treat a 0-minute road as 1. Floyd–Warshall is 10¹⁵ operations. DFS order does not give shortest distances.
More Coding Interview Problems questions
- Problem: A graph of flights has prices; find the cheapest price from src to dst using at most k stops (Bellman–Ford limited to k + 1…
- Problem: Count connected components of an undirected graph given as an edge list on n nodes. cpp int find(vector<int>& p, int x) { return…
- Problem: Return the k-th largest value in a stream of scores using a min-heap of size k. python import heapq def kthlargest(a, k): h = []…
- Problem: From n = 10⁶ log entries, return the k = 10 most frequent error codes. Which approach is the most efficient?
- Problem: Merge k sorted lists of order timestamps into one sorted list. python import heapq def mergek(lists): h = [(l[0], i, 0) for i, l…
- Problem: Maintain the median of a stream with two heaps (max-heap for the lower half, min-heap for the upper half). python import heapq…