Shortest Graph Path and Minimum-Mismatch Label Walk
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given an undirected, unweighted graph on n vertices numbered 0 through n - 1 and an edge list edges, implement:
def shortest_and_label_similar_paths(
n: int,
edges: List[List[int]],
s: int,
t: int,
names: List[str],
target: List[str],
) -> List[List[int]]:
The function solves two independent tasks on the same graph and returns [shortest_st_path, best_label_walk]:
- Fewest-hop path (
stot): Find a path[s, ..., t]connecting vertexsto vertextusing the minimum possible number of edges (whens == t, this is[s], using0edges; in general, a path ofkvertices traversesk - 1edges). Return[]iftcannot be reached froms. When multiple shortest paths share the minimum hop count, return the lexicographically smallest vertex list. - Minimum-mismatch label walk: Every vertex
vcarries a string tagnames[v]. Given a desired tag sequencetargetof lengthm, choosemvertices[v_0, v_1, ..., v_{m-1}]such that every consecutive pair(v_k, v_{k+1})shares an edge in the graph (vertices and edges may repeat) and the mismatch count — the number of positions0 <= k < mwherenames[v_k] != target[k]— is as small as possible. Return[]whentargetis empty (m == 0) or when no validm-vertex walk exists anywhere in the graph. When multiplem-vertex walks tie on the fewest mismatches, return the lexicographically smallest vertex list.
Examples
Example 1
Input:
n = 6
edges = [[0, 2], [2, 5], [0, 1], [1, 5], [1, 3], [3, 4]]
s = 0, t = 5
names = ["red", "tan", "tan", "blue", "gold", "blue"]
target = ["red", "blue", "blue", "gold"]
Output:
[[0, 1, 5], [0, 1, 3, 4]]
For the first task, both [0, 1, 5] and [0, 2, 5] reach 5 from 0 in 2 hops, and [0, 1, 5] wins lexicographically (1 < 2 at index 1). For the second task, walking [0, 1, 3, 4] visits tags ["red", "tan", "blue", "gold"], mismatching target only at index 1 (1 mismatch total; no 4-vertex walk achieves 0 mismatches).
Example 2
Input:
n = 4
edges = [[1, 2]]
s = 0, t = 3
names = ["k", "m", "n", "p"]
target = ["n", "m", "n"]
Output:
[[], [2, 1, 2]]
Vertices 0 and 3 are isolated, so no path connects 0 to 3 ([]). Meanwhile, alternating across the single edge between 1 and 2 gives [2, 1, 2], matching ["n", "m", "n"] with 0 mismatches.
Constraints
1 <= n <= 10^40 <= len(edges) <= 10^4, with0 <= u, v < nandu != v(parallel duplicate edges may appear)0 <= s, t < nlen(names) == n, where eachnames[v]is a non-empty string0 <= len(target) <= 10^3
Step-by-step walkthrough
Understand both path problems and the tie-breaking rule
We are given one undirected, unweighted graph on vertices
0 .. n - 1and asked to solve two tasks on it, returning[part_a_path, part_b_walk]:- Part A (Unweighted shortest path): Find a shortest path of vertices
[s, ..., t]from startsto targett, or[]iftcannot be reached froms(when non-empty, its edge length islen(path) - 1). - Part B (Label-similar walk): Given vertex labels
names[0 .. n - 1]and a target label sequencetarget[0 .. m - 1], find a sequence ofmvertices[v_0, v_1, ..., v_{m-1}]where every consecutive pair(v_i, v_{i+1})shares an edge in the graph, minimizing how many positionsihavenames[v_i] != target[i]. Return[]if nom-vertex walk exists (for instancem >= 2in an edgeless graph).
Notice two crucial details:
- In Part B, vertices may repeat (
[2, 1, 2]in Example 2 is valid because consecutive vertices are adjacent)—in graph terms, this is a walk, not a simple path. - When multiple optimal paths or walks tie, the judge expects the lexicographically smallest vertex list (for example, in Example 1 both
[0, 1, 5]and[0, 2, 5]reach5in2edges, and[0, 1, 5]wins because1 < 2at index 1). Designing both algorithms to break ties from left to right guarantees exact matches on every test.
- Part A (Unweighted shortest path): Find a shortest path of vertices
Build a deduplicated, sorted adjacency list
Both parts repeatedly ask: "Among all neighbors of
uthat keep us on an optimal solution, which neighbor has the smallest ID?" If we store each vertex's neighbors in aset(removing any duplicate edges) and then sort each set in ascending order0 .. n - 1, the very first valid neighbor we encounter in aforloop is automatically the smallest!def build_neighbors(n: int, edges: List[List[int]]) -> List[List[int]]: """Build a sorted, duplicate-free adjacency list for vertices 0..n-1.""" # neighbor_sets[u]: set of distinct vertices sharing an undirected edge with u. neighbor_sets: List[Set[int]] = [] for _ in range(n): neighbor_sets.append(set()) for u, v in edges: neighbor_sets[u].add(v) neighbor_sets[v].add(u) # Sorting each neighbor list ascending lets greedy scans pick the smallest vertex ID first. neighbors: List[List[int]] = [] for nearby in neighbor_sets: neighbors.append(sorted(nearby)) return neighborsPart A — Run BFS backward from t, then walk downhill from s
In an unweighted graph, breadth-first search (BFS) discovers vertices in non-decreasing order of hop count in O(n + E) time.
How do we guarantee the lexicographically smallest shortest path from
stot? Run BFS backward fromt! That fillsdist_to_target[v]= minimum edges needed to reachtfromv(-1if unreachable). Ifdist_to_target[s] == -1, return[]. Otherwise, start atcurr = sand repeatedly step to the first (smallest) neighbornxtsatisfyingdist_to_target[nxt] == dist_to_target[curr] - 1:Edges: [[0, 2], [2, 3], [0, 1], [1, 3]], s = 0, t = 3 1 (dist=1) / \ (d=2) 0 3 (dist=0) neighbors[0] = [1, 2] (sorted!) \ / At 0 (dist 2): first neighbor with dist 1 is 1 -> step to 1 2 (dist=1) At 1 (dist 1): first neighbor with dist 0 is 3 -> step to 3 Result: [0, 1, 3] (beats [0, 2, 3])def bfs_distances(neighbors: List[List[int]], source: int) -> List[int]: """Return shortest unweighted hop counts from source to every vertex (-1 if unreachable).""" # dist[v]: fewest edges between source and v, or -1 if unvisited. dist = [-1] * len(neighbors) dist[source] = 0 queue = deque([source]) while queue: u = queue.popleft() for v in neighbors[u]: # Mark dist[v] as soon as v is enqueued so each vertex enters the queue at most once. if dist[v] == -1: dist[v] = dist[u] + 1 queue.append(v) return dist def shortest_path(neighbors: List[List[int]], s: int, t: int) -> List[int]: """Return the lexicographically smallest shortest s->t path, or [] if unreachable.""" # Run BFS backward from t so dist_to_target[v] stores remaining hops from v to t. dist_to_target = bfs_distances(neighbors, t) if dist_to_target[s] == -1: return [] path = [s] curr = s while curr != t: # Because neighbors[curr] is sorted ascending, the first neighbor that steps # 1 hop closer to t gives the lexicographically smallest shortest path. for nxt in neighbors[curr]: if dist_to_target[nxt] == dist_to_target[curr] - 1: curr = nxt break path.append(curr) return pathPart B — Why brute force and greedy label matching fail
Trying all
m-vertex sequences takes O(n^m) time, which is astronomical forn = 10^4andm = 10^3.A greedy strategy—starting at a vertex that matches
target[0]and picking a matching neighbor at each step—is fast, but it gets fooled whenever matching early traps you in a bad neighborhood:Component 1: 0('a') --- 1('x') Component 2: 2('b') --- 3('c') --- 4('c') Target: ['a', 'c', 'c'] Greedy starts at 0('a') -> forced to [0, 1, 0] ('a', 'x', 'a') -> 2 mismatches! Optimal pays 1 mismatch up front at 2('b') -> [2, 3, 4] ('b', 'c', 'c') -> 1 mismatch!What we need from step
steponward depends only on(step, current_vertex)—the textbook signature of dynamic programming.Fill the mismatch DP table backward from the end of target
Just as running BFS backward from
tlet us build Part A's path from left to right, filling our DP table backward fromstep = m - 1down to0lets us build Part B's walk from left to right and break ties in lexicographic order!Define
dp[step][v]as the minimum label mismatches on the suffixtarget[step:]for a walk standing at vertexvat indexstep:- Base case (
step = m - 1): No more edges are needed, sodp[m - 1][v]is0ifnames[v] == target[m - 1], else1. - Transition (
step = m - 2down to0): Fromv, the walk must move to some neighbornxtinneighbors[v]:dp[step][v] = (1 if names[v] != target[step] else 0) + min(dp[step + 1][nxt] for nxt in neighbors[v]). Ifvhas no neighbors (neighbors[v]is empty),best_nextstaysfloat("inf"), sodp[step][v]becomesinf(an isolated vertex cannot continue a walk of 2+ vertices).
Each layer loops over all
nvertices and scans each undirected edge from both endpoints, taking O(n + E) work per layer and O(m * (n + E)) time overall—around3 * 10^7simple operations atn = 10^4, E = 10^4, m = 10^3.INF = float("inf") # dp[step][v]: minimum mismatches on target[step:] when the walk is at vertex v at 'step'. # Filling backward from step = m - 1 down to 0 lets us reconstruct forward from step = 0. dp = [None] * m # Base case at the final target position: 0 if vertex v's label matches, else 1. last_row: List[float] = [] last_label = target[m - 1] for v in range(n): last_row.append(int(names[v] != last_label)) dp[m - 1] = last_row # Backward transition: choose each vertex's best neighbor from the next step's row. # Isolated vertices have no neighbors, so best_next stays INF (cannot continue a walk). for step in range(m - 2, -1, -1): next_row = dp[step + 1] want_label = target[step] curr_row: List[float] = [] for v in range(n): best_next = INF for nxt in neighbors[v]: if next_row[nxt] < best_next: best_next = next_row[nxt] curr_row.append(best_next + int(names[v] != want_label)) dp[step] = curr_row- Base case (
Reconstruct the optimal walk from front to back
Once
dp[0]is ready:- Find
min_mismatches = min(dp[0]). If it equalsINF, no walk of lengthmexists anywhere in the graph—return[]. - Pick the smallest starting vertex
curr = dp[0].index(min_mismatches)(list.indexreturns the first/smallest index matchingmin_mismatches). - For
step = 1 .. m - 1, subtract the mismatch paid atcurronstep - 1:needed_remaining = dp[step - 1][curr] - int(names[curr] != target[step - 1]). Scanneighbors[curr](already sorted!) and jump to the firstnxtwithdp[step][nxt] == needed_remaining.
def most_similar_path(neighbors: List[List[int]], names: List[str], target: List[str]) -> List[int]: """Return the lexicographically smallest walk of len(target) vertices minimizing label mismatches.""" n = len(neighbors) m = len(target) if m == 0: return [] INF = float("inf") # dp[step][v]: minimum mismatches on target[step:] when the walk is at vertex v at 'step'. # Filling backward from step = m - 1 down to 0 lets us reconstruct forward from step = 0. dp = [None] * m # Base case at the final target position: 0 if vertex v's label matches, else 1. last_row: List[float] = [] last_label = target[m - 1] for v in range(n): last_row.append(int(names[v] != last_label)) dp[m - 1] = last_row # Backward transition: choose each vertex's best neighbor from the next step's row. # Isolated vertices have no neighbors, so best_next stays INF (cannot continue a walk). for step in range(m - 2, -1, -1): next_row = dp[step + 1] want_label = target[step] curr_row: List[float] = [] for v in range(n): best_next = INF for nxt in neighbors[v]: if next_row[nxt] < best_next: best_next = next_row[nxt] curr_row.append(best_next + int(names[v] != want_label)) dp[step] = curr_row # If every starting vertex has cost INF, the graph has no walk of m vertices. min_mismatches = min(dp[0]) if min_mismatches == INF: return [] # Reconstruct forward from step = 0, always picking the smallest vertex ID that stays optimal. curr = dp[0].index(min_mismatches) walk = [curr] for step in range(1, m): mismatch_at_prev = int(names[curr] != target[step - 1]) needed_remaining = dp[step - 1][curr] - mismatch_at_prev for nxt in neighbors[curr]: if dp[step][nxt] == needed_remaining: curr = nxt break walk.append(curr) return walk- Find
Trace Example 1 through both algorithms
Example 1 has
n = 6, edges0-2, 2-5, 0-1, 1-5, 1-3, 3-4,s = 0, t = 5,names = ['red', 'tan', 'tan', 'blue', 'gold', 'blue'], andtarget = ['red', 'blue', 'blue', 'gold']:Graph: 0('red') --- 1('tan') --- 3('blue') --- 4('gold') | | 2('tan') --- 5('blue') Sorted neighbors: 0:[1, 2] 1:[0, 3, 5] 2:[0, 5] 3:[1, 4] 4:[3] 5:[1, 2] Part A (BFS from t = 5): dist_to_target = [2, 1, 1, 2, 3, 0] Start curr = 0 (dist 2): neighbors [1, 2] -> both have dist 1, pick smallest -> curr = 1 At curr = 1 (dist 1): neighbors [0, 3, 5] -> 5 has dist 0 -> curr = 5 Part A result: [0, 1, 5] Part B (Backward DP for target = ['red', 'blue', 'blue', 'gold']): vertex v: 0 1 2 3 4 5 names[v]: 'red' 'tan' 'tan' 'blue' 'gold' 'blue' ------------------------------------------------------------ dp[3] (want 'gold'): 1 1 1 1 0 1 dp[2] (want 'blue'): 2 2 2 0 2 1 (v=3 matches 'blue' + dp[3][4]=0) dp[1] (want 'blue'): 3 1 2 2 1 2 (v=1 pays 1 + dp[2][3]=0 -> 1) dp[0] (want 'red'): 1 3 3 2 3 2 (v=0 matches 'red' + dp[1][1]=1) Forward rebuild (min_mismatches = 1): step 0: smallest v with dp[0][v] == 1 is v = 0 -> walk = [0] step 1: needed = 1 - 0 = 1; neighbors [1, 2] -> dp[1][1] == 1 -> walk = [0, 1] step 2: needed = 1 - 1 = 0; neighbors [0, 3, 5] -> dp[2][3] == 0 -> walk = [0, 1, 3] step 3: needed = 0 - 0 = 0; neighbors [1, 4] -> dp[3][4] == 0 -> walk = [0, 1, 3, 4]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque def build_neighbors(n: int, edges: List[List[int]]) -> List[List[int]]: """Build a sorted, duplicate-free adjacency list for vertices 0..n-1.""" # neighbor_sets[u]: set of distinct vertices sharing an undirected edge with u. neighbor_sets: List[Set[int]] = [] for _ in range(n): neighbor_sets.append(set()) for u, v in edges: neighbor_sets[u].add(v) neighbor_sets[v].add(u) # Sorting each neighbor list ascending lets greedy scans pick the smallest vertex ID first. neighbors: List[List[int]] = [] for nearby in neighbor_sets: neighbors.append(sorted(nearby)) return neighbors def bfs_distances(neighbors: List[List[int]], source: int) -> List[int]: """Return shortest unweighted hop counts from source to every vertex (-1 if unreachable).""" # dist[v]: fewest edges between source and v, or -1 if unvisited. dist = [-1] * len(neighbors) dist[source] = 0 queue = deque([source]) while queue: u = queue.popleft() for v in neighbors[u]: # Mark dist[v] as soon as v is enqueued so each vertex enters the queue at most once. if dist[v] == -1: dist[v] = dist[u] + 1 queue.append(v) return dist def shortest_path(neighbors: List[List[int]], s: int, t: int) -> List[int]: """Return the lexicographically smallest shortest s->t path, or [] if unreachable.""" # Run BFS backward from t so dist_to_target[v] stores remaining hops from v to t. dist_to_target = bfs_distances(neighbors, t) if dist_to_target[s] == -1: return [] path = [s] curr = s while curr != t: # Because neighbors[curr] is sorted ascending, the first neighbor that steps # 1 hop closer to t gives the lexicographically smallest shortest path. for nxt in neighbors[curr]: if dist_to_target[nxt] == dist_to_target[curr] - 1: curr = nxt break path.append(curr) return path def most_similar_path(neighbors: List[List[int]], names: List[str], target: List[str]) -> List[int]: """Return the lexicographically smallest walk of len(target) vertices minimizing label mismatches.""" n = len(neighbors) m = len(target) if m == 0: return [] INF = float("inf") # dp[step][v]: minimum mismatches on target[step:] when the walk is at vertex v at 'step'. # Filling backward from step = m - 1 down to 0 lets us reconstruct forward from step = 0. dp = [None] * m # Base case at the final target position: 0 if vertex v's label matches, else 1. last_row: List[float] = [] last_label = target[m - 1] for v in range(n): last_row.append(int(names[v] != last_label)) dp[m - 1] = last_row # Backward transition: choose each vertex's best neighbor from the next step's row. # Isolated vertices have no neighbors, so best_next stays INF (cannot continue a walk). for step in range(m - 2, -1, -1): next_row = dp[step + 1] want_label = target[step] curr_row: List[float] = [] for v in range(n): best_next = INF for nxt in neighbors[v]: if next_row[nxt] < best_next: best_next = next_row[nxt] curr_row.append(best_next + int(names[v] != want_label)) dp[step] = curr_row # If every starting vertex has cost INF, the graph has no walk of m vertices. min_mismatches = min(dp[0]) if min_mismatches == INF: return [] # Reconstruct forward from step = 0, always picking the smallest vertex ID that stays optimal. curr = dp[0].index(min_mismatches) walk = [curr] for step in range(1, m): mismatch_at_prev = int(names[curr] != target[step - 1]) needed_remaining = dp[step - 1][curr] - mismatch_at_prev for nxt in neighbors[curr]: if dp[step][nxt] == needed_remaining: curr = nxt break walk.append(curr) return walk def shortest_and_label_similar_paths(n: int, edges: List[List[int]], s: int, t: int, names: List[str], target: List[str]) -> List[List[int]]: neighbors = build_neighbors(n, edges) return [shortest_path(neighbors, s, t), most_similar_path(neighbors, names, target)]✅ Submit now — all tests should pass.
Intuition & how it works
Both parts use the same "solve backward, reconstruct forward" pattern so every step knows the exact future cost before choosing a move:
- Part A (Unweighted shortest path): Picture dropping a stone on destination
t: breadth-first search (BFS) (a graph traversal that visits vertices layer by layer in order of increasing edge count) labels every vertex with its remaining hop count tot. Starting ats, we simply walk "downhill" one hop at a time, always taking the lowest-numbered neighbor on ties so the resulting path is lexicographically smallest (earliest in left-to-right dictionary comparison, like[0, 1, 3]before[0, 2, 3]). - Part B (Label-similar walk): Picture planning an
m-day road trip across cities where dayiwants city labeltarget[i]and you are allowed to revisit cities—forming a walk (a sequence of adjacent vertices that may repeat vertices and edges, unlike a simple path which visits each vertex at most once). Using dynamic programming (DP) (a method that solves multi-step optimization problems by caching optimal answers to smaller subproblems in a table), we work backward from daym - 1down to day0sodp[step][v]records the fewest mismatches needed to finishtarget[step:]starting from vertexv.
Naive approaches fail on both correctness and runtime. Depth-first search in Part A finds a path rather than a shortest one, while enumerating all m-vertex walks in Part B takes O(n^m) exponential time. Even greedy label matching in Part B fails, and forward DP with parent pointers breaks ties from the back of the walk instead of the front.
Let's trace a 3-vertex line 0 - 1 - 2 with names = ['a', 'b', 'c'], s = 0, t = 2, and target = ['a', 'c', 'b']:
- Part A: BFS from
t = 2computesdist_to_target = [2, 1, 0], and walking downhill from0steps0 -> 1 -> 2. - Part B: Day
2('b') givesdp[2] = [1, 0, 1]. Day1('c') givesdp[1] = [1, 2, 0](for example,v = 2matches'c'and steps to1for0 + 0 = 0). Day0('a') givesdp[0] = [2, 1, 3]—showing why greedy fails: starting at matchingv = 0costs2mismatches, whereas starting atv = 1gives walk[1, 2, 1]('b', 'c', 'b') with only1mismatch!
Complexity
Let n be the number of vertices, E the number of input edges, and m = len(target).
- Building
neighbors— Time: O(n + E log n), Space: O(n + E). Inserting each edge into endpoint sets takes O(n + E) time, and sorting each vertex's unique neighbors (at mostn - 1per vertex,2Eentries total) takes O(E log n) time. - Part A (
shortest_path) — Time: O(n + E), Space: O(n). Each vertex enters the BFS queue at most once becausedist[v]is set on push, scanning each adjacency list at most once during BFS and at most once per path vertex during reconstruction. - Part B (
most_similar_path) — Time: O(m * (n + E)), Space: O(m * n). Each of them - 1DP transitions visits allnvertices and scans all2Eneighbor entries (~3 * 10^7elementary steps atn = 10^4, E = 10^4, m = 10^3), while storing allmrows of lengthn(10^7numbers at the limits) supports O(m + E_walk) forward reconstruction.
Edge cases
- Start equals target (
s == t):dist_to_target[s] == 0, thewhile curr != tloop does not run, and Part A returns[s](0edges). - Unreachable
tin Part A:dist_to_target[s] == -1returns[]for Part A while Part B still finds an optimal walk in any component that has edges (as in Example 2). - Empty target (
m == 0): Part B immediately returns[]. - Single-label target (
m == 1): No edges are traversed, so even an isolated vertex with zero edges is valid;dp[0]simply picks the smallest vertex matchingtarget[0](or0if none match). - Edgeless graph with
m >= 2: Every vertex hasneighbors[v] == [], sodp[0]is allinfand Part B returns[]. - Walks that bounce back and forth (
[0, 1, 0, 1]): Handled naturally becausedp[step][v]imposes no visited-set restriction.
Common mistakes
- Leaving adjacency lists in raw input order. With edges
[[0, 2], [2, 3], [0, 1], [1, 3]], unsorted neighbors explore2before1and return[0, 2, 3]instead of[0, 1, 3]. - Marking BFS vertices visited on
popleft()instead of onappend(). The same unpopped vertex gets pushed repeatedly by multiple neighbors, bloating queue size and runtime to O(E). - Forbidding repeated vertices in Part B. Requiring a simple path changes Part B from O(m * (n + E)) DP into an NP-hard problem and breaks cases like
target = ['a', 'b', 'a', 'b']on a single edge0 - 1. - Initializing
best_next = 0instead offloat("inf")for vertices with no neighbors. An isolated vertex cannot advance to stepstep + 1, so giving it0lets invalid multi-step walks teleport out of isolated nodes. - Using forward DP with parent pointers when lexicographic tie-breaking is tested. Forward DP picks ties at the last vertex first; on edge
0 - 1withnames = ['b', 'a']andtarget = ['b', 'b'],[0, 1]and[1, 0]tie at 1 mismatch, and picking the smallest ending vertex0reconstructs[1, 0]instead of[0, 1]. - Top-down recursion over
m = 1000steps in Python. Recursion depth1000hits Python's default call-stack limit (RecursionError), whereas iterative bottom-up loops use O(1) stack frames.
Alternative approaches
- Forward BFS from
sin Part A: With sorted neighbor lists, standard BFS fromsrecording the first-discovered parent actually reaches vertices in lexicographic shortest-path order too, though proving that requires an induction over queue order, whereas backward BFS + downhill greedy walk is self-evidently minimal at every hop. - Forward DP when any optimal walk is accepted: If tie-breaking order does not matter, filling
cost[step][v]forward from0tom - 1with aparent[step][v]table has the exact same O(m * (n + E)) time and O(m * n) space.
Follow-up questions
- How would you adapt the shortest-path algorithm if each edge carried a non-negative weight rather than unit cost? Replace BFS with Dijkstra's algorithm (a shortest-path search that uses a min-heap priority queue to always expand the closest unsettled vertex next), running backward from
tinO((n + E) log n)time. Froms, step to the smallest neighbornxtsatisfyingdist[curr] == weight(curr, nxt) + dist[nxt]. If zero-weight edges can appear, also track minimum hop counts tot(or visited vertices) so the reconstruction cannot loop around a zero-weight cycle. - How could you lower the
O(m * n)space footprint of the label-matching DP while still reconstructing an optimal walk? If only the minimum mismatch count is needed, keep justcurr_rowandnext_rowforO(n)space. To still reconstruct the full walk inO(n * sqrt(m))memory, checkpoint only everyB = int(sqrt(m))-th DP row during the backward pass; during forward reconstruction, recompute theBrows of the current block from the next checkpoint, doubling total time to save ~30x memory atm = 1000. As a practical constant-factor improvement in Python, storing each row inarray.array('H')(unsigned 16-bit ints, usingm + 1as infinity since mismatches never exceedm <= 1000) shrinks memory by more than 10x over Pythonlistobjects. - What happens to the complexity and algorithm if the label sequence must be matched by a simple path without repeated vertices? The problem becomes NP-hard: if every vertex has label
'a'andtargetisncopies of'a', finding a zero-mismatch simple path is equivalent to finding a Hamiltonian path (a path in a graph that visits every single vertex exactly once). For small graphs (n <= 20), you can run bitmask DP (dynamic programming where an integer's binary bits record which vertices have already been visited) over(visited_mask, current_vertex)inO(2^n * n^2)time; for larger graphs (nin the thousands), you must fall back to branch-and-bound search with pruning or heuristic search.
Follow-up questions
- How would you adapt the shortest-path algorithm if each edge carried a non-negative weight rather than unit cost?
- How could you lower the `O(m * n)` space footprint of the label-matching DP while still reconstructing an optimal walk?
- What happens to the complexity and algorithm if the label sequence must be matched by a simple path without repeated vertices?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array