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.
A PR adds a nested loop that appears O(n*m) where n is number of users and m is number of groups; assume n and m can both be in the tens of thousands. As reviewer, how do you assess the performance risk, what data and tests would you request, and how would you recommend optimizing it? Provide concrete alternative approaches.
Sample Answer
Direct answer
Don't guess at the performance risk, ask for the actual expected scale of n and m in production, then reason about it using Big O notation, a way to describe how an algorithm's run time grows as its input grows. A nested loop checking group membership for every user against every group is O(n*m) work (n times m operations); swapping the inner check for a set or hash lookup usually turns it into roughly O(n+m).
Structured elaboration
Assess the risk: ask what n and m actually are in production today, and their growth trend, not just "tens of thousands" in the abstract. O(n*m) at 100 users is invisible; at 10,000 it is not.
Request data: ask for, or add, a benchmark or test using production-representative sizes, and check whether this runs on every request (much worse) or in a background or batch job (more tolerable, but still worth fixing before it becomes the bottleneck).
Recommend optimizing: the usual fix for "is X in this collection" checked repeatedly is to build a set or hash index of the smaller collection once, then do average-case O(1) membership checks inside the loop, turning O(n*m) into roughly O(n+m).
Concrete alternatives beyond a set: if this is database-backed, push the membership logic into a single indexed query or join instead of looping in application code at all. If it must stay in memory and the groups are static across the request, precompute the set once outside the loop rather than rebuilding it per user.
Worked example
Trace it by hand with a small example: 4 users, 3 groups, checking whether each user belongs to a group they were assigned. The nested-loop version compares every user against every group: 4 x 3 = 12 comparisons in the worst case. Building a set of the 3 group IDs first costs 3 operations, then each of the 4 users does one average-case O(1) lookup, so total work is roughly 3 + 4 = 7 operations instead of 12. Scaled to the size named in the question, n = m = 10,000: the nested loop does up to 10,000 x 10,000 = 100,000,000 comparisons, while the set-based version does roughly 10,000 + 10,000 = 20,000 operations, a gap of about 5,000x at that size, the kind of difference that turns a fast endpoint into a timeout.
Illustrative (not executed) code showing the shape of the fix:
# O(n*m): nested loop
result = []
for user in users:
for group in groups:
if user.group_id == group.id:
result.append(user)
break
# O(n+m): index the smaller side once
group_ids = {g.id for g in groups} # built once
result = [user for user in users if user.group_id in group_ids]
Trade-offs and pitfalls
Not every nested loop needs this treatment. If n and m are both small and bounded, a fixed list of five config options, the O(n*m) version is simpler to read and the "optimization" adds complexity for no real benefit. The reviewer's job is to ask about actual scale before insisting on a rewrite. A common wrong turn is fixating on the algorithmic complexity while missing that the real fix might be a database query instead of loading everything into application memory in the first place.
Medium: Create a short rubric (4–6 criteria) you would use to evaluate code clarity during code review that balances readability, performance, and maintainability. Explain how you weight conflicting criteria when they trade off.
Sample Answer
Direct answer
Score a change against five criteria, readability, correctness and safety, maintainability, performance, and testability, each on a simple 1-5 scale, then break ties with a stated priority order rather than a strict weighted sum: correctness always wins first, and performance only overrides readability when there's a real, demonstrated need, not a hypothetical one.
Structured elaboration
- Readability and intent (heaviest weight). Clear naming, small functions, a logical structure, and a short comment where intent genuinely isn't obvious from the code alone. This is what determines how expensive every future change to this code will be.
- Correctness and safety (high weight). Edge cases handled, input validated, errors handled rather than swallowed, and passing tests. This one is close to non-negotiable: a readable change that's wrong is still wrong.
- Maintainability (moderate weight). Duplication removed rather than copy-pasted, components decoupled, and a clear public interface. Ask whether this change makes the NEXT change to this area easier or harder.
- Performance (lighter weight, situational). Whether the algorithmic complexity is appropriate for the expected data size, not a micro-benchmarked improvement measured in isolated nanoseconds that nobody will ever notice in production.
- Testability (lighter weight). Is the new logic actually covered by a test, and is it structured so it CAN be tested without heavy, brittle mocking?
How to weight conflicts. When performance and readability conflict, default to readability unless there's real evidence of a need, a benchmark, a known hot path, or a user-visible complaint, since premature optimization that sacrifices clarity is a far more common mistake in review than an under-optimized path that turns out to matter. When maintainability and short-term velocity conflict, prefer maintainability, but if a shortcut is taken anyway, track it explicitly with a TODO and a ticket rather than letting it pass silently.
Worked example
A concrete PR (pull request): it extracts a repeated validation block into a shared helper function, but the helper is named generically (doCheck) and is called from three unrelated modules. Scoring it against the rubric: readability 3 out of 5 (works, but the name doesn't say what it actually validates); maintainability 4 out of 5 (removes real duplication across three modules, a genuine improvement); correctness 5 out of 5 (behavior-preserving, has passing tests); performance not really applicable here; testability 4 out of 5 (the helper is small and easy to unit test in isolation). The net call: the underlying design decision, extracting the duplication, is correct, so request one specific, scoped fix (rename the helper to describe what it actually checks) rather than asking for a broader rewrite.
Trade-offs and pitfalls
The biggest pitfall in using any numeric rubric is treating the total score as an objective verdict: two very different profiles, for example all 3s across the board versus one 5 and one 1, can add up to a similar total but represent very different actual risk, so the rubric is a structure for the conversation, not a replacement for reading the diff. A second pitfall is applying it identically regardless of context, a small internal tool and a payment-processing module should not weight correctness the same way in practice, even though the rubric's criteria stay the same.
Describe concrete tactics for using code reviews as a mentoring tool for junior engineers. Include how you structure comments, what to pair-program versus comment, how to provide targeted learning resources, and how to measure progress over time for the mentee.
Sample Answer
Direct answer
Treat code review as one of several teaching tools, not the only one: use written comments for things that are efficient to explain in text, switch to pairing for anything that needs real back-and-forth, and track whether the same class of comment keeps recurring as the honest signal of whether the mentee is learning, not just complying.
Structured elaboration
Structuring comments
Lead with the "why," not just "change this to that." Separate must-fix from optional or learning-opportunity comments explicitly, so the mentee isn't guessing at severity. Ask a question ("what happens if this list is empty?") instead of dictating the fix when the goal is for them to reason through it themselves; state it directly when time pressure or risk is high enough that the learning moment can wait.
Pair-programming versus commenting
Pair when the concept is genuinely new to them, a new pattern or a new part of the codebase, or when a comment thread has gone back and forth more than twice without converging. Use written comments for anything they've seen before and just need a nudge on, since it's asynchronous and doesn't interrupt their flow.
Targeted learning resources
Link to the specific doc, prior PR (pull request), or style-guide section that addresses the exact gap, not a generic "read the docs on X." Even better: point to a real example already in the codebase that does it well, since it's concrete and has already passed review.
Measuring progress
Track whether the same category of comment (e.g. "add error handling," "extract this function") shows up less often across their later PRs. A good sign is the mentee starting to anticipate the class of feedback you'd give and addressing it before you comment. A bad sign is the same class of feedback repeating PR after PR with no change in how the code arrives.
Worked example
Mentoring a junior engineer over a couple of months: early PRs draw frequent comments on missing error handling and untested edge cases. When they hit an unfamiliar part of the codebase (an async job queue), that becomes a pairing session rather than a comment thread, since it's genuinely new. For a recurring "extract this into a function" pattern, the mentor points them at a specific earlier PR in the codebase that does it well, rather than a generic style guide link. The measurable, honest signal by the third or fourth PR: the error-handling comments mostly stop appearing, and their tests start covering edge cases unprompted, not a fabricated precise percentage.
Trade-offs and pitfalls
Mentoring through review can tip into micromanaging, rewriting their solution in comments instead of letting them arrive at it themselves. It can also become one-sided, where the mentor never learns anything from the mentee's perspective on the code. A common wrong turn is being so gentle that a genuinely blocking issue reads as optional and ships anyway, which helps no one.
A PR contains 120 small 'WIP' commits and non-descriptive commit messages. As a reviewer, describe your approach to make the review efficient: propose whether to ask the author to squash, draft a suggested squashed commit message, and explain how to preserve important history while improving reviewability.
Sample Answer
Direct answer
I'd ask the author to squash locally before I do a real review, since reviewing 120 undifferentiated "WIP" commits one by one wastes everyone's time and hides the actual shape of the change; but I'd also make sure nothing meaningful gets thrown away in the process, and offer to do the squash myself in a scratch branch if the author can't or the team's policy restricts rewriting shared history.
Structured elaboration
Why ask for a squash here specifically. 120 commits with non-descriptive messages carries essentially zero information over one well-described commit; reviewing them individually adds review time without adding review value. The one real cost is losing any genuinely useful detail buried in an individual WIP commit (a debugging note, an intermediate approach that was tried and reverted), so the request isn't "just squash it," it's "squash it, and pull anything worth keeping into the final commit message or a comment first."
How. The author creates a backup branch first (so nothing is unrecoverable if the rebase goes wrong), then uses an interactive rebase to fold the 120 commits down to a small number of logical, reviewable ones, force-pushing the result to their own PR branch (never to a shared branch other people have already based work on).
Preserving what matters. Any commit that represents a genuinely separate concern (a schema migration, a breaking API change) stays its own commit rather than getting folded into the "everything else" bucket; anything else, including all the pure WIP noise, gets condensed.
Worked example
The PR implements search filters for a job listing page. A suggested squashed commit message for the bulk of the 120 commits:
Add search filters to job listing page
- Add filter UI components for location, role, and salary range
- Wire filter state to the existing search API request
- Add debounced input handling to avoid a request per keystroke
- Tests: unit tests for filter state logic, integration test for
the combined filter + search request path
Follow-up: filter presets (saved searches) intentionally deferred
to a separate PR, tracked in issue #482.
If a few of the 120 commits represent something genuinely separable, say, an unrelated dependency bump that got tangled in along the way, I'd ask for that one to stay its own commit rather than get folded in, so it can be reviewed and reverted independently of the search-filter work itself.
Trade-offs and pitfalls
Requiring a squash before review adds a round trip (the author has to do the rebase, then wait for review) compared to just wading through all 120 commits as-is, which is a real cost for a genuinely time-pressured change; for something urgent, reviewing the overall diff directly (ignoring individual commit boundaries entirely) and asking for a cleanup squash after approval, rather than before, is a reasonable alternative. The most common pitfall is squashing too aggressively and losing a commit that actually mattered, like a migration or a breaking change that needed its own clear point in history, which is exactly why the request should always be "squash the noise, keep anything that's a real, separate concern," not "collapse everything into one commit.
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.
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.