Data Structures & AlgorithmsHardProduct Company SDE · graph round
Problem: Using Dijkstra from node 0 on the undirected graph with edges (0,1,2), (1,2,2), (0,2,5), (2,3,1), how many nodes have shortest distance at most 5? Run the code.
Problem: Using Dijkstra from node 0 on the undirected graph with edges (0,1,2), (1,2,2), (0,2,5), (2,3,1), how many nodes have shortest distance at most 5? Run the code.
import heapq
edges = [(0, 1, 2), (1, 2, 2), (0, 2, 5), (2, 3, 1)]
g = [[] for _ in range(4)]
for u, v, w in edges:
g[u].append((v, w))
g[v].append((u, w))
d = [float('inf')] * 4
d[0] = 0
pq = [(0, 0)]
while pq:
du, u = heapq.heappop(pq)
if du > d[u]:
continue
for v, w in g[u]:
if du + w < d[v]:
d[v] = du + w
heapq.heappush(pq, (d[v], v))
print(sum(1 for x in d if x <= 5))What is printed?- A. 4
- B. 3
- C. 2
- D. 1
Correct answer: A. 4
The distances are 0, 2, 4 and 5 for nodes 0 to 3 (0-1-2-3 costs 5), so all four are within 5.
More Coding Interview Problems questions
- Problem: How many simple paths go from 0 to 3 in the undirected graph with edges 0-1, 1-2, 2-3, 3-0 and the chord 0-2? Run the DFS code…
- Problem: How many ordered pairs (a, b) with 1 <= a <= b <= 20 have gcd(a, b) = 1? Run the code. python from math import gcd print(sum(1…
- Problem: How many integers in [1, 100] are the product of exactly two distinct primes? Run the code. python def primesupto(n): s = [True]…
- Problem: What is the minimum length of a contiguous subarray of [1, 2, 3, 4, 5, 6, 7, 8] with sum at least 15? Run the two-pointer code…
- Problem: What is the integer floor of the square root of 10^12? Use binary search. python lo, hi = 0, 10 12 while lo < hi: mid = (lo + hi…
- Problem: Split [7, 2, 5, 10, 8] into 2 contiguous parts to minimise the largest part sum. What is the answer? Run the brute-force code…