Test Plan for Straight-Line vs Path Word Search
Arrays & HashingModel answerLast updated
Build a TDD plan, concrete cases, property invariants and stress tests for two grid word-search functions that must disagree on key inputs.
You are handed two grid-search functions and asked to own their quality end to end:
in_line(grid, word) -> bool— true whenwordoccupies consecutive cells along one fixed straight direction, chosen from the eight compass directions, without turning.on_path(grid, word) -> bool— true whenwordcan be spelled by a walk of four-directionally adjacent cells where no cell is visited twice; turns are allowed.
Shared conventions: an empty word is always True (even on an empty grid), an empty grid with a non-empty word is False, comparison is case-sensitive with no normalization unless the spec says otherwise, and malformed input (ragged rows, cells that are not single characters, a non-string word) raises an error.
Produce a test plan and a test-driven development workflow: enumerate concrete cases with expected outcomes for both functions, say which cases are the most discriminating and why, explain how you would layer unit tests, property-based tests and stress tests, define pass/fail criteria, and note how test pressure shapes the implementation (recursion depth, pruning, complexity). There is no automatic judge — argue your plan in prose and back it with a reference implementation sketch.
Hints
Hint 1
Start by writing down the contract for each function and one failing test per contract clause — the vocabulary of the two functions is where most bugs hide.
Hint 2
Hunt for inputs where the two functions must give different answers; those expose far more than cases where both agree.
Hint 3
Your grid test doubles as an oracle: a hand-rolled brute-force enumerator is fast enough at 4x4 and lets you check thousands of random inputs.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Pin the contract first
Before a single test exists, state the rules and turn each into an assertion. This is the main signal the interviewer is looking for.
in_line | on_path | |
|---|---|---|
| Movement | one of 8 fixed offsets, never changes | 4-neighbour steps, may turn |
| Cell reuse | none (a line is automatically simple) | forbidden |
| Typical failure mode | a turn slipped in, or a line wrapped across row boundaries | a visited flag not reset, or a repeated cell accepted |
Empty word → True; empty grid with non-empty word → False; case-sensitive; malformed input raises. Encode every one of those clauses as its own test so a regression names itself.
The TDD loop
Red → green → refactor, driven by one small case at a time: degenerate cases first, then the discriminating cases, then properties, then stress. The ordering matters because the stress tests are the ones that force real design changes (iterative DFS, letter-count pruning), and you only want that pressure once the behaviour is nailed down. Refactors that should never break a test: extracting the direction tuples, adding input validation, adding the pruning step.
Concrete cases
| # | Case | Grid | Word | in_line | on_path |
|---|---|---|---|---|---|
| 1 | empty grid | [] | "A" | F | F |
| 2 | empty word | [["A"]] and [] | "" | T | T |
| 3 | single cell hit / miss | [["A"]] | "A" / "B" | T / F | T / F |
| 4 | word longer than cell count | [["A"]] | "AA" | F | F |
| 5 | horizontal and vertical, both orders | ABC/DEF/GHI | ABC, CBA, ADG, GDA | T | T |
| 6 | four diagonals | same | AEI, IEA, CEG, GEC | T | F |
| 7 | turn required | same | ABE | F | T |
| 8 | row wrap | ABC/DEF | CD | F | F |
| 9 | revisit temptation | AB/CD | ABA | F | F |
| 10 | legal repeat | AAA/AAA | AAAA | F | T |
| 11 | many starts, one works | AAB/AAA | AAB | T | T |
| 12 | absent word | ABC/DEF | XYZ | F | F |
| 13 | case sensitivity | [["a"]] | "A" | F | F |
| 14 | malformed input | ragged rows, [["AB"]], word=None | — | raises | raises |
Cases 6 and 7 are the highest-value ones: they are the only entries where the two functions must disagree, so passing them proves the two implementations are genuinely distinct rather than one wrapping the other. Case 8 catches the classic flattened-index bug where the arithmetic slips from the end of one row into the start of the next. Case 9 catches a missing visited check or a missing reset; case 10 catches the over-correction, where visited is never cleared on backtrack and legal repeats are wrongly rejected. Pair them deliberately — they fail in opposite directions.
Property-based layer
With small random grids (1–5 by 1–5) over a two-letter alphabet, collisions and backtracking happen constantly. Assert:
- Planting: write a random word along a random line (for
in_line) or a random self-avoiding 4-walk (foron_path); the result must beTrue. - Reversal:
f(g, w) == f(g, w[::-1])for both — the direction set and the adjacency relation are symmetric. - Grid symmetry: results are invariant under transpose and 90° rotation.
- Prefix closure: if
f(g, w)holds, so doesf(g, w[:k]). - Count pruning: if a letter occurs more times in
wthan in the grid, the answer isFalse. - Implication: a horizontal or vertical
in_linehit implies anon_pathhit. - Brute-force oracle: enumerate all lines and all simple paths at ≤ 4×4 and compare.
Stress and stack depth
- Deep positive: a 100×100 grid with the word laid out as a boustrophedon snake over every cell — 10,000 characters, ten times Python's default recursion limit. It must return
Truewith noRecursionError; this test is what converts the DFS to an explicit stack. - Adversarial negative: a 50×50 grid of
"A"with word"A"*30 + "B". Letter-count pruning must reject it in milliseconds; without pruning the search explodes. - Scale positive: a 1000×1000 grid, 20-letter word, within an agreed time budget.
Pass/fail criteria
All table cases pass exactly, including exception types. Property suites run at 500+ examples each with shrinking clean. Stress tests finish under a fixed CI budget (say 2 s each) with no recursion error. Line and branch coverage ≥ 95% on both functions. Nothing flaky: fixed seeds for the generator and the stress grids.
What the pressure does to the implementation
in_line is O(R·C·8·L) time, O(1) space — check the end cell is in bounds before scanning, so most candidates are rejected immediately. on_path is worst-case O(R·C·3^(L−1)) time once the first step is taken, O(L) stack plus O(R·C) visited space. Pruning by letter counts and starting from the rarer end of the word do not change the bound but defuse the realistic adversarial inputs, which is exactly what the stress tests document.
from collections import Counter
DIRS8 = [(0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)]
DIRS4 = [(0,1),(1,0),(0,-1),(-1,0)]
def _validate(grid, word):
if not isinstance(word, str):
raise TypeError("word must be str")
if not isinstance(grid, list) or any(not isinstance(r, list) for r in grid):
raise TypeError("grid must be list of lists")
if grid and any(len(r) != len(grid[0]) for r in grid):
raise ValueError("ragged")
if any(not isinstance(ch, str) or len(ch) != 1 for r in grid for ch in r):
raise ValueError("cells must be single chars")
def in_line(grid, word):
_validate(grid, word)
if word == "":
return True
if not grid or not grid[0]:
return False
R, C, L = len(grid), len(grid[0]), len(word)
for r in range(R):
for c in range(C):
if grid[r][c] != word[0]:
continue
for dr, dc in DIRS8:
er, ec = r + dr*(L-1), c + dc*(L-1)
if not (0 <= er < R and 0 <= ec < C):
continue
if all(grid[r+dr*i][c+dc*i] == word[i] for i in range(L)):
return True
return False
def on_path(grid, word):
_validate(grid, word)
if word == "":
return True
if not grid or not grid[0]:
return False
R, C = len(grid), len(grid[0])
need = Counter(word)
have = Counter(ch for row in grid for ch in row)
if any(n > have[ch] for ch, n in need.items()):
return False
if need[word[0]] > need[word[-1]]: # start from the rarer end
word = word[::-1]
for sr in range(R):
for sc in range(C):
if grid[sr][sc] != word[0]:
continue
stack = [(sr, sc, 0, {(sr, sc)})]
while stack:
r, c, i, seen = stack.pop()
if i == len(word) - 1:
return True
for dr, dc in DIRS4:
nr, nc = r+dr, c+dc
if 0 <= nr < R and 0 <= nc < C \
and (nr, nc) not in seen and grid[nr][nc] == word[i+1]:
stack.append((nr, nc, i+1, seen | {(nr, nc)}))
return False
Common mistakes: testing only cases where the two functions agree, forgetting the empty-word convention, treating the empty grid as an error instead of False, asserting exception messages instead of types, and writing the stress test last with no time budget so it silently slows the suite.