Skip to content

Lesson 17 of 27Talk it through

Testing Your Own Solution

Test like an engineer in the last ten minutes: three deliberate passes, quick asserts, stress tests that shrink failures, and properties to check.

13 min read0/5 questions

You finish coding with eight minutes left. You read the code top to bottom, it looks right, and you say "I think that works." The interviewer then asks you to run "abba", and the answer is wrong. Rereading your own code mostly confirms what you meant to write, not what you wrote. Testing is a separate skill, and in an interview it is also a separate line on the scorecard.

This lesson is how to test in the time you have: which cases to pick, how to check them with and without the ability to run code, how to stress test and shrink a failure, and the short list of bugs that cause most wrong answers.

How interviewers score testing

At most large companies, testing and verification is scored separately from problem solving and coding. What earns the points is unprompted testing. If you wait until the interviewer asks "how would you test this?", you get partial credit at best. If you say "before I call this done, let me test three cases" and do it, you get the full row, even when your first pass finds a bug.

Finding your own bug is a good outcome. Interviewers know everyone writes bugs under time pressure. They are watching whether you catch it before they do, and whether the fix is calm and targeted.

The other thing they watch: testing means running the code, in your head or in the editor, on specific inputs with specific expected outputs. "Let me look it over" is not testing. "For [2, 7] with target 9, I expect [0, 1]; i is 0, the map is empty, I store 2..." is testing.

The three passes

You rarely have time for more than three cases, so each must earn its place.

  1. The given example. It confirms the main path works and that you read the output format correctly (indices or values? sorted? 0- or 1-based?). It rarely finds subtle bugs, because you probably designed the code around it.
  2. A tiny edge case. Empty input, one element, all equal, target missing. Pick the one your code is most likely to mishandle, which you know because you wrote it. These catch crashes and wrong defaults.
  3. One nasty case built from the algorithm. Ask: "what situation does my code handle in a special way, and what input makes that happen in an awkward spot?" For a sliding window, a repeat that sits outside the current window. For binary search, a target at index 0 or past the end. For a graph, a cycle or a disconnected node.

Before each case, say the expected answer out loud first. If you compute the expected value by running your code in your head, you will reproduce your own bug and agree with it. Work out the answer from the problem statement, then trace the code, then compare.

How to trace well is covered in Dry Runs and Invariants, and how to pick edge cases from the constraint lines in Edge Cases from Constraints. This lesson is about building a testing habit on top of those.

Quick check
Your sliding-window solution for 'longest substring without repeating characters' passes 'abcabcbb', '' and 'aaaa'. Which extra case is most likely to find a remaining bug?
Need a nudge? A hint rules out a wrong answer.

When you can run code: a table of asserts

On CoderPad-style editors you can usually run code. Use that, but do it in a structured way: a small table of (input, expected) pairs and a loop that prints what failed. It takes about a minute to write, it shows the interviewer exactly what you are checking, and you rerun it after every fix.

Here is a common sliding-window solution with a real bug. Run it.

Python
def longest_unique(s: str) -> int: seen = {} left = best = 0 for right, ch in enumerate(s): if ch in seen: left = seen[ch] + 1 # bug hiding here seen[ch] = right best = max(best, right - left + 1) return best cases = [ ("abcabcbb", 3), # the given example ("", 0), # empty ("a", 1), # single character ("aaaa", 1), # all the same ("abba", 2), # repeat that sits LEFT of the window]for s, want in cases: got = longest_unique(s) status = "ok " if got == want else "FAIL" print(f"{status} {s!r:12} want {want} got {got}")
Output
Press Run (⌘ Enter) to see what happens.

Four of five pass, including the given example. On "abba", when the final a arrives, left is 2 (it moved past the first b). The old a is at index 0, so left = 0 + 1 moves the window backwards and counts bba as unique. The fix is left = max(left, seen[ch] + 1). Make it and run again.

Two habits make this work in an interview. Print the input with each failure, so you never have to guess which case broke. And keep the table: when you fix one bug, the earlier cases tell you that you did not create another.

When you cannot run code

Some interviews happen in a shared doc or a plain editor with no run button. Then you trace by hand, and the trick is to be visible and selective:

  • Write the input and the expected answer as a comment above your trace.
  • Keep a small table of the variables that change, one row per iteration. Update it in the editor so the interviewer can follow.
  • Trace the nasty case, not the long example. Six iterations of "abba" find more than twenty iterations of a long string.
  • When the loop does the same thing repeatedly, say so and skip ahead: "the next three steps just extend the window; at index 5 the repeat arrives."

If you are short on time, trace the nasty case only and name the other two: "I would also check empty input, which returns 0 because the loop never runs."

Stress testing, and shrinking what fails

Brute Force First introduced the stress test: a slow, obviously correct solution, a random generator, and a loop that compares them. In an interview you will rarely have time to write the whole thing, but in an online assessment with hidden tests, or a take-home, it is the most reliable tool you have. Three details separate a useful stress test from a useless one.

Keep inputs small and values crowded. Random strings over 26 letters of length 100 almost never contain the awkward pattern. Strings over "abc" of length 0 to 12 hit repeats, ties and empty input constantly. Small inputs also keep the brute force fast.

Seed the generator. random.seed(1) makes the failure reproducible, so you can rerun after a fix and know you tested the same inputs.

Shrink the failure. A random failing input like "baababbcac" is hard to reason about. Shrinking means repeatedly deleting one element and keeping the smaller input if it still fails, until nothing can be deleted. What is left is the smallest case that shows the bug.

Python
import random def brute(s): best = 0 for i in range(len(s)): for j in range(i, len(s)): if len(set(s[i:j + 1])) == j - i + 1: best = max(best, j - i + 1) return best def fast(s): seen = {} left = best = 0 for right, ch in enumerate(s): if ch in seen: left = seen[ch] + 1 # the same bug seen[ch] = right best = max(best, right - left + 1) return best def fails(s): return fast(s) != brute(s) def shrink(s): # Keep deleting single characters while the case still fails changed = True while changed: changed = False for i in range(len(s)): smaller = s[:i] + s[i + 1:] if fails(smaller): s, changed = smaller, True break return s random.seed(1)for trial in range(2000): s = "".join(random.choice("abc") for _ in range(random.randint(0, 12))) if fails(s): print(f"trial {trial}: failing input {s!r}") small = shrink(s) print(f"shrunk to {small!r}: fast={fast(small)} brute={brute(small)}") breakelse: print("2000 random tests agree")
Output
Press Run (⌘ Enter) to see what happens.

The stress test found a messy failure on its third try, and the shrinker reduced it to "abba", the same case a careful human would pick. Fix fast with max(left, ...) and the loop reports that all 2,000 tests agree.

Shrinking a failing input
b
0
a
1
a
2
b
3
a
4
b
5
b
6
c
7
a
8
c
9
fast = 4brute = 3

The random failure. Ten characters, and it is not obvious why the answers differ.

1/5
Put it in order5 steps

Put the stress-and-shrink routine in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Property checks when there is no brute force

Sometimes no simple brute force exists, or several outputs are correct ("return any valid pair", "any topological order"). Then check properties: facts that must be true of any correct output, whatever the exact answer.

  • Sorting-style outputs: the output is sorted, and it is a permutation of the input (Counter(out) == Counter(inp)).
  • Conservation: a sum, count or set of elements is preserved.
  • Validity: for Two Sum, nums[i] + nums[j] == target and i != j. For a topological order, every edge goes forward.
  • Idempotence: running it twice changes nothing. Merging already merged intervals, or normalising a normalised path, should return the same thing.
  • Bounds: the answer is between 0 and n, or never above the brute-force upper bound.

Here is Merge Intervals with a subtle bug, checked by three properties on random input.

Python
import random def merge(intervals): out = [] for start, end in sorted(intervals): if out and start <= out[-1][1]: out[-1][1] = end # bug: should be max(out[-1][1], end) else: out.append([start, end]) return out def check(intervals, out): # 1. sorted, and no two output intervals overlap or touch for a, b in zip(out, out[1:]): if not a[1] < b[0]: return "output overlaps or is unsorted" # 2. every input interval sits inside some output interval for s, e in intervals: if not any(o[0] <= s and e <= o[1] for o in out): return f"input {[s, e]} is not covered" # 3. every output start and end is a real input value starts = {s for s, _ in intervals} ends = {e for _, e in intervals} for s, e in out: if s not in starts or e not in ends: return f"output {[s, e]} was invented" return None random.seed(4)for trial in range(1000): xs = [] for _ in range(random.randint(1, 5)): a = random.randint(0, 10) xs.append([a, a + random.randint(0, 6)]) problem = check(xs, merge(xs)) if problem: print(f"trial {trial}: {xs} -> {merge(xs)}") print("broken property:", problem) breakelse: print("1000 random inputs keep every property")
Output
Press Run (⌘ Enter) to see what happens.

The check never computed the right answer, yet it caught the bug: [0, 3] contains [1, 1], and overwriting the end shrank the merged interval to [0, 1]. Properties are also what you say when asked "how would you test this in production?", where there is no answer key either.

Quick check
A function returns any valid topological order of a DAG. Which check is the right test?
Need a nudge? A hint rules out a wrong answer.

The bug catalogue

Most wrong answers in interview code come from a short list. Knowing the list tells you which nasty case to test.

  • Window and range bounds. right - left versus right - left + 1, range(n - 1) that skips the last item, a left pointer that moves backwards (the bug above).
  • Mutating while iterating. Removing from a list or dict you are looping over skips items or raises RuntimeError: dictionary changed size during iteration. Loop over a copy, or build a new collection.
  • Aliasing. [[0] * n] * m in Python and new Array(m).fill([]) in JavaScript share one row. result.append(path) in backtracking stores a reference that later changes; append path[:].
  • Integer division and rounding. In Python, (lo + hi) / 2 is a float and cannot index a list. In JavaScript, / never floors, so use Math.floor. Negative numbers floor differently from how they truncate: -7 // 2 is -4.
  • State that survives between test cases. Platforms like LeetCode call your function many times in one process. A module-level memo, a class attribute, or a mutable default argument keeps the previous test's answers.

That last one is the nastiest, because every test passes alone and fails when run after another. Run this.

Python
memo = {} # module level: survives between tests def min_coins(coins, amount): if amount == 0: return 0 if amount in memo: return memo[amount] best = float("inf") for c in coins: if c <= amount: best = min(best, 1 + min_coins(coins, amount - c)) memo[amount] = best return best print(min_coins([1, 5], 10)) # first test caseprint(min_coins([1, 2], 10)) # second test case reuses the old memomemo.clear()print(min_coins([1, 2], 10)) # the honest answer
Output
Press Run (⌘ Enter) to see what happens.

The fix is to create the memo inside the function call (or use functools.cache on an inner function), so each test case starts clean.

Predict the outputPython

What does this print?

grid = [[0] * 3] * 2
grid[0][0] = 5
print(grid)
Need a nudge? Hints walk you through it.
Match the pairs0/5 matched

Match each bug to the smallest test that exposes it.

Choose an item, then its match on the other side.
Key terms
unprompted testing
Testing your code before the interviewer asks. It is often scored as its own rubric row.
nasty case
An input built to send your code down its special path in an awkward position, such as a repeat outside the window.
stress test
Comparing a fast solution against a trusted brute force on many small random inputs.
shrinking
Repeatedly removing parts of a failing input while it still fails, to get the smallest case that shows the bug.
property check
Testing facts every correct output must satisfy (sorted, a permutation, every edge forward) instead of comparing to one answer.
aliasing
Two names or slots referring to one object, so a change through one appears through the other.
stale state
Data such as a memo or class attribute that survives from one test case into the next and corrupts it.