Code Review and Working with Existing Codebases Questions
Reviewing others' code and navigating unfamiliar systems: giving and receiving actionable review feedback, spotting correctness and design issues, and reading and understanding large or legacy codebases before changing them. Covers collaborative coding norms, incremental change in shared repositories, and verifying changes against existing behavior. The team-facing side of day-to-day engineering.
You're reviewing a junior engineer's O(n^2) implementation that removes duplicates from an array. Describe how you'd review the code, suggest an O(n) improvement, and outline tests and benchmarks you would request before approving the change for production.
Sample Answer
Direct answer
Review this the way you'd review any performance-sensitive change from someone newer to the codebase: confirm correctness first (edge cases, ordering guarantees), explain clearly why the current approach is quadratic, propose an O(n) fix using a hash set for membership checks, and before approving for production, ask for tests proving the new version behaves identically to the old one, plus, if this runs on a genuinely hot path, evidence the fix is actually faster, not just an assumption that it must be.
Structured elaboration
Why it's O(n squared). A naive dedup checks if x not in output_list inside a loop. Membership testing on a list (or a similar linear structure like a Java ArrayList) is itself O(n), since it may scan the whole list to answer "is x in here." Doing that check once per element, for n elements, makes the whole function O(n) times O(n), which is O(n^2).
The O(n) fix. Track "have I seen this value" with a hash set instead of a list. Checking membership in a hash set is O(1) on average (amortized, meaning an occasional slower lookup during an internal resize averages out across many calls), so doing that check n times is O(n) total instead of O(n^2).
Review checklist beyond the algorithm. Does the fix need to preserve the original relative order of first occurrences? A hash set alone doesn't preserve order, but tracking "seen" in a set while still appending to a separate output list, as below, does. Are the elements guaranteed to be hashable? Is a None/null value handled the same as any other value, or does it need special casing?
Worked example
The O(n) fix, run against a sample array:
def remove_duplicates(arr):
seen = set()
out = []
for x in arr:
if x not in seen:
seen.add(x)
out.append(x)
return out
sample = [4, 1, 4, 2, 1, 3, 4, 5, 2]
print("input: ", sample)
print("output:", remove_duplicates(sample))
Output:
input: [4, 1, 4, 2, 1, 3, 4, 5, 2]
output: [4, 1, 2, 3, 5]
A regression test proving the new function matches the old (naive) one on the same input, which is exactly the kind of test to request before approving:
def remove_duplicates_naive_on2(arr):
out = []
for x in arr:
if x not in out:
out.append(x)
return out
print("naive output:", remove_duplicates_naive_on2(sample))
print("same result:", remove_duplicates(sample) == remove_duplicates_naive_on2(sample))
Output:
naive output: [4, 1, 2, 3, 5]
same result: True
An idempotence check, since "run it twice, get the same result" is a cheap property test worth having:
def test_idempotent():
once = remove_duplicates(sample)
twice = remove_duplicates(once)
assert once == twice
test_idempotent()
print("idempotence test: PASS")
Output:
idempotence test: PASS
Tests and benchmarks to request before approving: unit tests for an empty array, a single element, all duplicates, all unique, and unhashable elements (decide up front: raise a clear error, or document that unhashable input isn't supported); a regression test asserting the new function's output matches the old function's output on realistic, production-shaped data, generalizing the equivalence check above beyond one hand-picked sample; and if this runs on a hot path, evidence reported qualitatively rather than as a single wall-clock number, for example "the old approach's runtime visibly grows worse as input size grows while the new one stays roughly flat," since a wall-clock timing claim is environment-dependent and not something a reviewer can independently verify from a PR (pull request) description.
Trade-offs and pitfalls
The O(n) fix uses O(n) extra memory for the set, which matters if memory, not CPU (central processing unit), is the actual constraint. If the array must be deduplicated in place with no extra memory while preserving order, that's a real trade-off against a strict O(n) time bound, since some in-place approaches require sorting first, which changes the original order. It's also worth not over-applying this fix: if n is reliably small (a handful of items), the quadratic version's actual cost is negligible, and the review's energy is better spent asking where else in the codebase the same pattern shows up on data that actually can grow large.
You are reviewing a large refactor that touches core library internals. Outline a plan to split the change into incremental PRs that are safe to merge independently. Include a proposed sequence, how to keep the system working at each step, feature flagging, test strategies, and rollback points.
Sample Answer
Direct answer
I sequence the refactor so the public interface changes land first, additively, before internals move; I migrate call sites one at a time behind a feature flag with small commits that each leave the system green, and I pick a rollback point at every seam so the whole plan is expand-migrate-contract rather than one big merge.
Structured elaboration
Sequencing principle: expand, migrate, contract
- Expand: add the new internal implementation alongside the old one, without removing anything
- Migrate: switch call sites over incrementally, one at a time, behind a flag
- Contract: once every call site is migrated and validated in production, delete the old code path in its own final, low-risk pull request (PR, a proposed code change submitted for review)
Interface first
If the refactor changes a library's public interface, not just its internals, land the new interface signature first as a strictly additive change (a new method or overload alongside the old one) before implementation work even starts. This lets consumer teams see or start adopting the new shape while the internals are still being built, instead of waiting for one giant landing.
Verify against real consumers, not just the library's own tests
Before merging any internal change, run each consumer's recorded expectations of the library (its actual inputs and outputs, sometimes called a consumer-driven contract) against the new implementation. This catches the case where the internals pass the library's own unit tests but silently break an assumption a downstream consumer relied on that the library never tested itself.
Branching and commit order
Prefer small commits on a short-lived branch or trunk-based development, with the feature flag doing the isolation, over a long-lived branch. A stale long-lived branch reintroduces the exact big-bang-merge risk this plan exists to avoid. Order commits so each one compiles, passes CI (continuous integration, the automated build/test pipeline), and leaves the system deployable: add the new path unused, add the flag defaulting off, migrate the lowest-risk call site, validate, migrate the rest in ascending risk order, then remove the old path.
Test strategy at each step
- Characterization tests (tests that pin down what the old code currently does, written before touching it) on the existing implementation first
- Consumer contract tests run on every PR in the sequence, not only the last one
- Shadow-run the new path against the old path's output on real traffic where feasible, before flipping the flag for real
Rollback points
Every PR that flips a flag default is a rollback point: flipping the flag back is the fast rollback, no code revert or redeploy needed. The final "delete the old path" PR is the one true point of no return, so it ships last, only after a full soak period with the flag on.
flowchart LR
A["PR1: add new path, flag off"] --> B["PR2: add consumer contract tests"]
B --> C["PR3: implement new internals"]
C --> D["PR4: migrate lowest-risk consumer"]
D --> E["PR5-7: migrate remaining consumers"]
E --> F["PR8: delete old path"]
Worked example
Refactoring a core PaymentValidator library used by 4 internal services, changing its algorithm from a synchronous rule chain to a rule-table lookup for performance. PR1 adds validate_v2() alongside the existing validate(), unused, behind a payment_validator_v2 flag defaulting off, plus characterization tests pinning validate()'s current output on 50 representative inputs. PR2 adds contract tests recording each of the 4 consumers' actual usage patterns against validate(). PR3 implements validate_v2(), which must pass every contract test. PR4 migrates the lowest-risk consumer, an internal reporting service, behind its own flag, monitored for a week. PR5-7 migrate the remaining 3 consumers one at a time, with live payment processing last, each with its own soak period. PR8, once all 4 consumers are on v2 and soaked through a full billing cycle, deletes validate() and the flag. If PR5's shadow comparison shows a discrepancy in production, the rollback is flipping that one consumer's flag back, not reverting code.
Trade-offs and pitfalls
- Expand-migrate-contract takes longer in calendar time and leaves two code paths live temporarily, itself a maintenance cost and a place bugs can hide (fixing one path and forgetting the other)
- Skipping consumer contract tests and relying only on the library's own unit tests is the classic way this goes wrong: internals look correct in isolation but violate an assumption a consumer depended on
- A stale long-lived branch reintroduces the exact big-bang-merge risk the plan exists to avoid; if small trunk-based commits aren't feasible, that's a signal the split needs to be finer-grained, not a reason to accept one large final merge
- Deleting the old path before every consumer has soaked removes the rollback safety net that made the whole plan low-risk in the first place
You are reviewing a teammate's pull request that adds memoization to a function. What checks would you perform in code review to ensure correctness, memory safety, and thread-safety? Provide concrete review comments you might leave.
Sample Answer
Direct answer
Reviewing a memoization pull request (PR) means checking three separate things, not just "does it look right": is the cache key actually correct, is the cache's memory use bounded, and is it safe if the function can be called from more than one thread at once. Leave specific, line-referenced comments with a proposed fix, not a general "looks good."
Structured elaboration
Memoization means caching a function's return value keyed by its input, so a repeat call with the same input is served from the cache instead of recomputed.
Correctness
- Does the cache key capture every input that affects the output, including default/optional arguments and any instance state for a method? A key that's missing one input will return a stale, wrong answer for calls that only differ in that field.
- Is the function actually deterministic and side-effect-free for a given input? If it has a side effect (an increment, a log line, a downstream call), that side effect now only fires on a cache miss, which the PR should call out as an intentional, documented behavior change.
- Is there any invalidation path, or does a cached value live forever even after the underlying data it depends on changes?
Memory safety
- Is the cache bounded, for example an LRU (least-recently-used) cache with a maximum size, or a TTL (time-to-live) that expires old entries, or can it grow without limit and eventually cause an OOM (out-of-memory) failure on a long-running process?
- If the cache keys or values hold references to large or long-lived objects (like an instance whose method is being memoized), does the cache keep those objects alive longer than intended? That's a slow memory leak, not a crash, so it's easy to miss in a quick review.
Thread-safety
- If two threads call the function with the same new argument at almost the same moment, what happens? A plain dict/HashMap being read and written by two threads without synchronization can corrupt its internal structure, not just return a stale value.
- Is the "check cache, then compute, then store" sequence atomic, or can two threads both miss the cache and both do the (possibly expensive) work at once? That's usually acceptable for a pure read-through cache, but it should be a stated decision, not an accident.
Worked example
Concrete review comments for this PR, each pointing at a specific problem and a fix:
- "Nit: please add a test that calls this function twice with identical inputs and asserts the second call returns the cached result without re-running the underlying computation (for example by mocking the expensive call and asserting it was invoked once)."
- "This cache is an unbounded dict, so a long-running process will keep every distinct input in memory forever. Can we bound it, for example with
functools.lru_cache(maxsize=...)in Python, or an explicit LRU wrapper in other languages?" - "This cache isn't synchronized. If this function can be called from more than one thread, either guard the check-then-store sequence with a lock, or use a data structure built for concurrent access (a
ConcurrentHashMapin Java, or a dict behind an explicit lock in Python)." - "Key correctness: the cache key here only includes
user_id, but the function's output also depends onas_of_date. Two calls for the same user on different dates will incorrectly return the same cached value."
Trade-offs and pitfalls
A lock around the whole cache is simple but serializes every call, even ones for different keys; a per-key lock or a genuinely concurrent map avoids that contention at the cost of more complex code, worth it once the function is actually called concurrently at meaningful volume, not before. An unbounded cache is the fastest option and the easiest to get wrong in production, since it fails silently (memory just grows) until it doesn't. If the cached value is a mutable object, a caller who mutates what they got back can corrupt the cached copy for every future caller unless the function returns a defensive copy, that's a subtle correctness bug worth its own comment when the return type is mutable.
During a code review the author and reviewer disagree on an API naming decision that affects many callers. Describe a step-by-step conflict resolution you would follow as the reviewer to reach a pragmatic decision while preserving team trust, including whether to escalate, prototype alternatives, or perform a quick user impact analysis.
Sample Answer
Direct answer
Don't let the disagreement stay abstract: get concrete about what's actually at stake, how many callers exist and how costly a rename would be later, state your reasoning once clearly, and if it's still unresolved, use a fast, low-cost tiebreaker (a quick prototype, a third opinion, or an explicit decision-maker) rather than letting the thread drag on.
Structured elaboration
- Separate preference from cost. Ask explicitly whether this is reversible. An API used by many callers is expensive to rename later, a breaking change or a long deprecation, so the bar for insisting on a preferred name should scale with how many callers exist and how costly a change would be, not with how strongly either person feels.
- State your reasoning once, concretely, and ask for theirs. Name the specific downside, not just "I don't like this name": "
getUserreads as a lookup that returns null, but this always creates one if missing, that's surprising for the many call sites that assume a pure read." - If still unresolved, do a quick, cheap check instead of more debate. Grep the existing callers to see how the API is actually used, or spend ten minutes prototyping both names in real call sites to see which reads better. This replaces opinion with evidence.
- If still stuck, get a third opinion fast. A tech lead, or whoever owns that part of the API, makes the call; anyone involved can request this, and it's cheap to ask compared to letting the PR (pull request) stall.
- Once decided, commit and close the thread visibly. Whoever didn't get their preference says so out loud ("okay, going with X") so the disagreement doesn't linger as an unresolved grudge, and the reasoning gets written down briefly (in the PR or a short doc) so the next naming debate doesn't restart from zero.
Worked example
Two engineers disagree on getUser versus findOrCreateUser for a method with roughly forty existing call sites. The reviewer greps the callers and finds most assume a pure lookup with no side effects. Bringing that evidence back, "most callers don't expect this to write anything, the name should signal that," the author agrees the evidence changes the calculus, and they land on findOrCreateUser. A short note is added to the PR explaining the reasoning so a future reader understands why the name is what it is.
Trade-offs and pitfalls
Escalating to a tech lead for every minor naming choice trains the team to stop deciding things themselves. Conversely, letting every naming disagreement burn hours of back-and-forth stalls delivery on something that's often genuinely reversible later behind an alias. The failure mode to avoid is a reviewer pulling rank, "just do it my way, I'm the reviewer," instead of showing the reasoning; that resolves the immediate PR but erodes trust for the next one.
You observe several flaky tests in CI that pass locally but fail intermittently on the pipeline. As a reviewer and engineer, walk through your triage and remediation plan, and how you'd communicate status to the team while it's unresolved.
Sample Answer
Direct answer
Don't quarantine and forget. Flaky tests, tests that pass locally but fail intermittently in CI (continuous integration), erode trust in the whole suite fast. Confirm it's actually flaky rather than a real intermittent bug, isolate the likely cause, fix or explicitly quarantine it with a tracked owner, and keep the team visibly informed the whole time so people don't start treating red CI as normal.
Structured elaboration
Confirm it's flaky, not a real bug: re-run the specific test many times in isolation, and also alongside its usual neighbors. If it only fails in combination with other tests, that's a strong clue it isn't really about the test itself.
Common causes, checked in order:
- Timing or async: does it wait on a real signal that an async operation finished, or on a fixed sleep?
- Shared or leaked state: does it depend on data left behind by another test, or share a global or database row with a test running in parallel?
- Test order dependency: does it pass in isolation but fail only after a specific other test runs first?
- External dependency: does it hit a real network call, the system clock, or unseeded randomness?
Remediate: fix the root cause where possible, mock the external dependency, isolate test data, replace a sleep with waiting on the actual condition. If it can't be fixed immediately, quarantine it explicitly, skip it with a linked ticket and a named owner, rather than leaving it red and training people to ignore CI failures.
Communicate status: post in the team channel when a test is quarantined and why, keep a visible list of currently-quarantined tests so it doesn't become an invisible, growing pile, and set an expectation for when it'll be revisited, since "quarantined forever" behaves the same as deleted, but worse, because it still looks like coverage exists.
Worked example
A test for an async file-upload flow fails about 1 in 20 runs in CI but never locally. Re-running it 30 times in isolation, it passes every time. Re-running the full suite, it fails only when run after a specific test that doesn't clean up its own temp file. Root cause: the earlier test's leftover file makes the upload test see unexpected existing state. Fix: add proper teardown to the earlier test, and switch the flaky test's own wait off a fixed sleep and onto the actual upload-complete signal, reducing remaining timing risk too. Communication: a short note in the team channel when it's identified as flaky, not yet a merge blocker, and a follow-up once it's confirmed fixed.
Trade-offs and pitfalls
Automatically retrying a flaky test until it passes hides the problem instead of fixing it, and the underlying issue can silently get worse over time. Blocking all merges on every flaky failure without triage first punishes the whole team for one bad test and trains people to distrust CI. The right balance is quarantine with a named owner and a deadline, not indefinite silence in either direction.
Unlock Full Question Bank
Get access to all Code Review and Working with Existing Codebases interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.