Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: Maximum flow from s = 0 to t = 5 with Edmonds–Karp (BFS augmenting paths).
Problem: Maximum flow from s = 0 to t = 5 with Edmonds–Karp (BFS augmenting paths).
from collections import deque
cap = [[0]*6 for _ in range(6)]
for u, v, c in [(0,1,10),(0,2,10),(1,2,2),(1,3,4),(1,4,8),(2,4,9),(3,5,10),(4,3,6),(4,5,10)]:
cap[u][v] = c
def maxflow(s, t):
flow = 0
while True:
par = [-1] * 6; par[s] = s; q = deque([s])
while q and par[t] == -1:
u = q.popleft()
for v in range(6):
if par[v] == -1 and cap[u][v] > 0: par[v] = u; q.append(v)
if par[t] == -1: return flow
b, v = float('inf'), t
while v != s: b = min(b, cap[par[v]][v]); v = par[v]
v = t
while v != s: cap[par[v]][v] -= b; cap[v][par[v]] += b; v = par[v]
flow += b
print(maxflow(0, 5))What is printed?- A. 20
- B. 21
- C. 4
- D. 19
Correct answer: D. 19
Node 2 can receive 10 from the source but forward only 9 (to 4), so the cut 0→1 (10) + 2→4 (9) = 19 is the minimum and Edmonds–Karp reaches it. The source's out-capacity (and the sink's in-capacity) is 20, the cut around {0, 1, 2} is 21 but not minimal, and stopping after the first BFS path 0→1→3→5 gives only 4.
More Coding Interview Problems questions
- Problem: Does an undirected connected graph have an Euler path / Euler circuit? (count odd-degree vertices) python from collections import…
- Problem: Count Hamiltonian paths (ordered sequences visiting every vertex once) in a small undirected graph with bitmask DP. python n = 5…
- Problem: Reconstruct an actual longest strictly increasing subsequence with the O(n²) DP and parent pointers (the first maximal end index…
- Problem: Minimum number of single-character insertions plus deletions to turn a into b (no replacements). python def insdel(a, b): m, n =…
- Problem: Fibonacci modulo 10⁹ + 7 by 2 × 2 matrix exponentiation in O(log n). python MOD = 109 + 7 def mul(A, B): return [[(A[0][0]B[0][0]…
- Problem: Count balanced parenthesis strings with n pairs whose nesting depth never exceeds d (DP over position and current depth). python…