Sub topic 13
Explaining Your Approach in Reviews and Interviews
Earlier chapters showed how to build a brute-force solution, check that it is correct, estimate its cost, and turn it into something faster. This chapter covers how to explain that process to other people. In a technical interview, the interviewer judges your reasoning as much as your final code. In a code review, the reviewer has to trust your optimized solution without having watched you build it. A brute-force-first approach helps in both settings, but only when you explain it clearly.
This chapter assumes you can write and analyze the brute-force and optimized two-sum solutions from earlier chapters. It also assumes you know Big-O notation and have seen a randomized stress test.
Why Communication Is Part of the Solution
Starting with brute force can be read two ways. A listener may conclude that you could not think of anything better. Or they may see that you established a correct baseline on purpose and are now improving it. Your code can be identical in both cases. The explanation decides which one they hear.
Explaining your approach well does three things:
- It shows correctness early. Once the listener agrees the brute force is right, every later change is a smaller claim: "this faster version gives the same answers."
- It shows judgment. Stating the cost and comparing it to the input limits shows that you know when brute force is enough and when it is not.
- It makes the optimization traceable. If you name the wasted work in the brute force, the faster algorithm looks like a consequence of that observation, not a trick you happened to remember.
The Interview Flow
A good interview answer follows a steady sequence. You do not need to say each step out loud as a heading, but you should cover each one.
Step 1: Clarify before enumerating
Brute force depends on knowing exactly what counts as a candidate. Ask the questions that change the search space:
- Can the same element be used twice?
- Are values negative, zero, or duplicated?
- What should the function return when there is no answer?
- How large can the input be?
The last question matters most. An input limit of n ≤ 20 points toward subsets or exhaustive search. A limit of n ≤ 10^5 rules out anything quadratic. Asking about limits shows the interviewer that you will use them to make a decision.
Step 2: State the search space and the brute force together
Keep this short. For two-sum:
"Every candidate answer is a pair of distinct indices i < j. Brute force checks all n(n−1)/2 pairs and returns the first one whose values sum to the target. That's O(n²) time and O(1) extra space."
That sentence covers what is enumerated, how many candidates there are, and what it costs. It also commits you to a correctness argument: the brute force is correct because it checks every candidate.
Step 3: Decide out loud
Compare the cost to the limit using a rough operation budget. A common rule of thumb is about 10^7 to 10^8 simple operations per second in compiled languages, and less in Python.
"With n up to 10^5, that's about 5 × 10^9 pair checks, which is far too slow. So I'll use the brute force as a reference and look for the repeated work."
If the brute force does fit, say so and offer it: "n is at most 50, so 1,225 pairs is trivial. I'd ship the simple version unless you want me to optimize anyway." Many candidates skip this step and lose credit for the judgment it shows.
Step 4: Name the waste, then the fix
This step is the core of the explanation. Describe what the brute force recomputes:
"For each j, the inner loop scans all earlier elements looking for one value, target − nums[j]. That's a membership question, and I'm answering it by linear scan every time. A hash map of earlier values answers it in expected O(1)."
The optimization now follows directly from the waste you pointed out. The listener can check your reasoning instead of taking the trick on trust.
Step 5: Verify
After coding the fast version, trace one small example by hand. Mention that, given more time, you would stress-test it against the brute force. In a take-home or on-the-job setting, actually run that test.
Phrasing That Helps and Phrasing That Hurts
| Weak phrasing | Stronger phrasing | Why it is better |
|---|---|---|
| "I'll just do the dumb way first." | "I'll start with exhaustive search over all pairs so we have a correct baseline." | Presents brute force as a deliberate choice |
| "This is probably slow." | "This is O(n²); with n = 10^5 that's about 5 × 10^9 steps." | Gives a number the listener can check |
| "We can use a hash map." | "The inner loop repeats a lookup; a hash map makes each lookup O(1) expected." | Connects the fix to the waste |
| "I think it works." | "It matches the brute force on 1,000 random small inputs." | Replaces belief with evidence |
| "It's fast enough." | "Worst case is 2^20 ≈ 10^6 subsets times 20 additions, about 2 × 10^7 steps." | Shows the estimate behind the claim |
Explaining It in a Code Review
A code review needs the same reasoning, written down. The reviewer reads your code later, without you present, so the explanation has to live in the pull request description, the docstrings, and the tests.
Keep the brute force in the test suite
Keep the brute force when you ship the optimized version. Move it into the tests as a reference implementation. The reviewer then sees two things side by side: an obviously correct version and a fast version checked against it. The pattern below runs as one file. In a real project the two parts would live in a module and its test file.
import random
def two_sum_fast(nums, target):
"""Return indices (i, j) with i < j and nums[i] + nums[j] == target, or None.
Single pass with a dict of value -> earliest index seen so far.
Expected O(n) time, O(n) extra space.
Verified against _two_sum_reference in test_two_sum_matches_reference.
"""
seen = {}
for j, x in enumerate(nums):
if target - x in seen:
return (seen[target - x], j)
if x not in seen:
seen[x] = j
return None
def _two_sum_reference(nums, target):
"""Brute force over all pairs i < j. O(n^2). Test use only."""
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return (i, j)
return None
def test_two_sum_matches_reference(trials=2000, seed=0):
rng = random.Random(seed)
for _ in range(trials):
nums = [rng.randint(-5, 5) for _ in range(rng.randint(0, 8))]
target = rng.randint(-10, 10)
expected = _two_sum_reference(nums, target)
actual = two_sum_fast(nums, target)
assert (expected is None) == (actual is None), (nums, target, expected, actual)
if actual is not None:
i, j = actual
assert i < j and nums[i] + nums[j] == target, (nums, target, actual)
def test_edge_cases():
assert two_sum_fast([], 0) is None
assert two_sum_fast([3], 6) is None # cannot reuse one element
assert two_sum_fast([3, 3], 6) == (0, 1) # duplicates are allowed
assert two_sum_fast([-2, 7, 4], 2) == (0, 2) # negatives
if __name__ == "__main__":
test_two_sum_matches_reference()
test_edge_cases()
print("all tests passed")Some details in this example are there for the reviewer:
- The docstring states the complexity and points to the test that backs the correctness claim.
- The fixed seed makes a failure reproducible. A reviewer who sees a red build can rerun the exact case.
- The edge-case test turns the clarifying questions from the interview flow (reuse, duplicates, negatives, empty input) into permanent checks.
- The
if x not in seenguard keeps the earliest index for each value. Both versions still return a valid pair, so the test checks validity and existence, not exact equality.
A pull request description template
A short structure covers what a reviewer needs:
- Problem and limits. "Match pairs of orders summing to a refund amount; batches have up to 200,000 orders."
- Baseline. "The obvious pairwise check is O(n²), about 2 × 10^10 comparisons per batch, so it's too slow."
- Change. "Hash map of seen amounts replaces the inner scan; O(n) expected."
- Evidence. "Randomized test against the pairwise reference, 2,000 cases, fixed seed; edge cases listed in
test_edge_cases." - Trade-offs. "Uses O(n) extra memory. Hash-based worst case is not guaranteed; acceptable here because the keys are integers from our own system."
The trade-offs line matters most to an experienced reviewer. It shows you know where the new solution is weaker than the old one.
Common Mistakes
- Coding brute force without announcing it. The interviewer may think it is your final answer. Say what it is and why you are writing it.
- Spending too long on brute force. In a 45-minute interview, the brute-force description and cost should take a minute or two. Write the code only if the interviewer asks or if it is short.
- Skipping the cost estimate. Without it, moving to an optimization looks arbitrary.
- Claiming exact equality where only validity holds. If several answers are valid, say your test checks validity. Do not claim the two versions return identical output.
- Hiding the trade-off. Extra memory, a dependency on sorted input, or a worse worst case should be stated, not discovered later.
Adapting to the Listener
Different audiences need different amounts of detail. A senior interviewer may cut you off after the search-space sentence: "Yes, O(n²), what's better?" Go straight to the redundant work. A reviewer outside your area may need the input limits and the operation-count estimate spelled out before the optimization makes sense. In both cases the order stays the same: what is searched, what it costs, what is wasted, what fixes it, and how you know it works. Only the length changes.
Exercise
An interviewer asks you to find whether any subset of a list of up to 20 non-negative integers sums to a target. Write the two or three sentences you would say before writing any code.
Show answer
"Each candidate is a subset of the items, so there are 2^n of them, at most 2^20, which is about one million. Brute force tries every subset with a bitmask and sums its items, about 2 × 10^7 basic steps in the worst case, which fits the limit. Since all values are non-negative, I can also prune any branch whose running sum passes the target, but the plain version is already fast enough, so I'll start with it." A good answer states the search space, the count, the cost compared to the limit, and a decision.
Exercise
A reviewer comments on your PR: "How do I know the new O(n log n) scheduler gives the same results as the old O(n^2) one?" What should your reply point to, and what should be in the code to support it?
Show answer
Point to a randomized test that runs both versions on many small generated inputs with a fixed seed and asserts they agree (or, if several outputs are valid, that the new output is valid and exists exactly when the old one does). The old O(n^2) version should be kept as a reference function in the test suite, and the new function's docstring should name its complexity and the test that checks it. Edge cases such as empty input, ties, and duplicates should have their own explicit tests.
Exercise
Rewrite this interview statement to be more convincing: "My first idea is slow, so I'll use a hash map instead."
Show answer
Example: "The pairwise check is O(n^2), which for n = 10^5 is about 5 × 10^9 steps, which is too slow. Its inner loop just looks for one specific value among earlier elements. Storing earlier values in a hash map turns each lookup into expected O(1), giving O(n) overall with O(n) extra memory." The rewrite gives the cost as a number, names the repeated work, connects the hash map to that work, and states the trade-off.