Data Structures & AlgorithmsVery hardProduct company OA
Problem: Shortest route where exactly one road may be used at half price (one coupon). Dijkstra on states (junction, coupon used?).
Problem: Shortest route where exactly one road may be used at half price (one coupon). Dijkstra on states (junction, coupon used?).
import heapq
def coupon(n, edges, s, t):
g = [[] for _ in range(n)]
for a, b, w in edges: g[a].append((b, w)); g[b].append((a, w))
INF = 10**18; d = [[INF, INF] for _ in range(n)]
d[s][0] = 0; h = [(0, s, 0)]
while h:
c, u, used = heapq.heappop(h)
if c > d[u][used]: continue
for v, w in g[u]:
for nu, nc in ((used, c + w), (1, c + w // 2)) if not used else ((1, c + w),):
if nc < d[v][nu]: d[v][nu] = nc; heapq.heappush(h, (nc, v, nu))
return min(d[t])
E = [(0, 1, 4), (1, 3, 4), (0, 2, 2), (2, 3, 20), (3, 4, 1)]
print(coupon(5, E, 0, 4), coupon(5, E[:4], 0, 3))What is printed?- A. 9 8
- B. 7 6
- C. 7 12
- D. 13 6
Correct answer: B. 7 6
Each junction is split into two layers; using the coupon moves from layer 0 to layer 1 with cost ⌊w/2⌋. First query: 0 → 1 → 3 → 4 with the coupon on a road of weight 4 costs 2 + 4 + 1 = 7, cheaper than halving the 20-road (2 + 10 + 1 = 13). Second (target 3, without the last road): 2 + 4 = 6. Simply halving the heaviest road of the ordinary shortest path can fail when a longer path contains a much heavier road; the layered graph considers every choice and is O((V + E) log V).
More Coding Interview Problems questions
- Problem: Each grid cell has an arrow; moving along a cell's arrow is free, moving in any other direction costs 1 (you change the arrow)…
- Problem: Courses with prerequisites; at most k = 2 courses per semester. Exact DP over bitmasks of finished courses versus 'take the k…
- Problem: Count 'heavy pairs' i < j with a[i] > 2·a[j] in O(n log n) using a Fenwick tree over coordinate-compressed values (both x and 2x…
- Problem: A segment tree stores (sum, best prefix, best suffix, best subarray) per node to answer 'maximum subarray sum inside a[l..r]'…
- Problem: Smallest period of a log pattern from its KMP prefix function: per = n − π[n − 1], and s is a whole repetition only if per…
- Problem: Find the longest string that is a prefix of s, a suffix of s, and also occurs somewhere strictly inside (not as the prefix or the…