InterviewPrepKit

Home / Coding / Graphs

Minimum Genetic Mutation

medium Original ↗
Solving tips
  • Recognize shortest-path-on-unweighted-graph: genes are nodes, an edge joins genes differing in exactly one char, so fewest mutations = BFS distance.
  • BFS from startGene level by level; the level at which endGene is first dequeued is the answer, using a visited set to avoid cycles.
  • Generate neighbors by trying each of the 8 positions x 3 other letters (24 candidates) and keeping those in the bank set; return -1 if endGene not in bank.
  • Pitfall: don't use DFS and return the first path found (not guaranteed shortest); for very large graphs bidirectional BFS meeting in the middle is the standard speedup.

Problem

A gene string is 8 characters long, each from {'A', 'C', 'G', 'T'}. A mutation changes exactly one character to one of the other three. You’re given a startGene, an endGene, and a bank of valid gene strings.

Return the minimum number of mutations to transform startGene into endGene, where every intermediate gene (after each single mutation) must be present in bank. If endGene is unreachable under these rules, return -1.

Note: startGene itself need not be in bank, but endGene must be (otherwise it’s unreachable).

Examples

  • start = "AACCGGTT", end = "AACCGGTA", bank = ["AACCGGTA"]1 — one mutation at the last position.
  • start = "AACCGGTT", end = "AAACGGTA", bank = ["AACCGGTA","AACCGCTA","AAACGGTA"]3 — path AACCGGTT → AACCGGTA → AACCGCTA → AAACGGTA… (any valid 3-step chain).
  • start = "AAAAACCC", end = "AACCCCCC", bank = ["AAAACCCC","AAACCCCC","AACCCCCC"]3.
  • start = "AACCGGTT", end = "AACCGGTA", bank = []-1 — end not in bank, no path.

Constraints

  • len(startGene) == len(endGene) == 8; characters from {A, C, G, T}.
  • 0 <= len(bank) <= 10; each bank string has length 8.

Think about it first

Hint 1 Each valid gene is a node; two genes are connected by an edge if they differ in exactly one character. You want the shortest path (fewest edges) from start to end — a hallmark of BFS on an unweighted graph.
Hint 2 BFS level by level from start. The level index when you first pop end is the answer. Neighbors of a gene are the bank entries that differ from it in exactly one position (or, generate all 1-character mutations and keep those in the bank).
Hint 3 Because the alphabet is tiny (4 letters, 8 positions → 24 candidate mutations per gene) and the bank is small, either neighbor-finding works. Mark genes visited so you don't revisit. If BFS drains without reaching end, return -1.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.