Data Structures & AlgorithmsVery hardICPC regional · Product Company SDE
Problem: A directed graph has 4 vertices (0–3) and arcs with weights: 0→1 (4), 1→2 (−3), 0→2 (2), 2→3 (1), 1→3 (5), 3→1 (−1). Start with distance 0 at vertex 0 and infinity elsewhere. Run Bellman–Ford for exactly 2 rounds; each round relaxes all arcs once, in the order listed above. Count the successful relaxations, meaning the arcs that strictly lower some distance, over both rounds together.
- A. 7
- B. 4
- C. 10
- D. 12
Correct answer: A. 7
Round 1 lowers d1 = 4, d2 = 1, d3 = 2, d1 = 1 (4 relaxations); round 2 lowers d2 = −2, d3 = −1, d1 = −2 (3 more), so 7 — the cycle 1→2→3→1 has weight −3 and keeps improving. One round gives 4, three rounds give 10, and 12 counts every arc examined.
More Coding Interview Problems questions
- Array a = [4, 2, 6, 1, 5, 3, 3, 9, 2]. How many contiguous subarrays of length at least 3 have a sum divisible by 6?
- Array a = [3, 5, 8, 2, 7, 10, 4]. How many pairs of positions i < j have a[i] + a[j] equal to some value located strictly after position j?
- Sorted array b = [1, 2, 3, 4, 5, 7, 8, 9]. What is the largest product b[i] b[j] over index pairs with j - i >= 3?
- Sorted array [1, 3, 4, 6, 8, 9, 11]. How many index triples i < j < k satisfy c[k] - c[i] <= 4?
- How many strings of length 5 over the alphabet {a, b, c} have no two adjacent characters equal?
- How many non-empty subsets of {1, 2, 3, 4, 5, 6} have an XOR of their elements that is at least 4?