
Solving problems in coding interviews
Solving problems in coding interviews
Who is this for?
Software students and candidates preparing for algorithm problems and coding interviews. For people learning how to approach a question and explain their solution during an interview.
This lesson explains seven steps for solving an algorithm question: understand it, solve it manually, design a solution, challenge the idea, implement it, test it, and clean up the code.
Purpose of this lesson
- Understand why a consistent problem-solving process helps in coding interviews.
- Learn the seven steps for approaching an algorithm question.
- Apply those steps to a worked problem, from reading the question to tested and cleaned-up code.
Explanation, worked example and practice
Before you start
Basic programming: functions, conditionals, loops, lists, and dictionaries. Basic Python is enough to follow the examples.
Time to work through this lesson
2 h – 3 h · You do not need to finish in one sitting.
Time breakdown and assumptions
- Reading and examples
- 40 min – 50 minRead the seven-step method, trace Two Sum and study the examples.
- Exercises
- 40 min – 55 minAnswer the short questions, run the Two Sum checks and try the refactor.
- Assignment
- 40 min – 1 h 15 minApply all seven steps to image smoothing; implement, test and explain the costs.
For a first independent pass with the stated prerequisites: read carefully, try every exercise before opening its answer, allow for setup, debugging and one revision. Breaks, waiting for another person, optional further projects and repeated interview practice are extra. The project continues the same work across units; it is not rebuilt from scratch for every exercise.
Understand the idea
In a coding interview, you are given a problem. You are expected to write a working program and explain how you found the solution, why it works, and how much time and memory it needs. This lesson is about how to approach that task.
The time limit and the need to explain your thinking can make you rush, even when the problem is familiar. You might start coding before understanding the question, spend too long implementing a flawed idea, or forget to test. A routine you have rehearsed in practice makes it easier to remember where you are and what to check next.
We will first apply the process to Two Sum: find two different positions in a list whose values add to a given target. We will clarify the rules, solve a small input by hand, develop a solution idea and try to break it. Then we will write the Python code, test it and clean it up. In the final exercise, you will use the same seven steps on a different problem yourself.
You can work through the notes and exercises independently. Paper is enough to follow the reasoning. Running the code requires Python 3 and basic knowledge of lists, dictionaries, loops and functions; this lesson does not teach Python syntax from scratch.
An example of the question we will work through
In [4, 1, 6, 3], look for two values that add to 9. The values 6 and 3 do; their zero-based positions are 2 and 3, so the answer is [2, 3]. The lesson goes beyond finding this one answer: we will examine how to make the procedure work correctly on other inputs as well.
Try it yourself
In a practice interview you have an idea but cannot explain why it works. What should you do before implementing it?
Show a worked solution
Write the steps on paper and walk a small input through them. If you cannot predict a step or explain what a stored value means, the design still has a gap. Resolve that gap, or name it and investigate it with a small example.
Resources
Code and original product screens keep their original language. The lesson explains them in your selected language.

Solving problems in coding interviews
The seven steps of problem solving
Understand → solve manually → design on paper → challenge the idea → implement → test → simplify and clean up.
Explanation, worked example and practice
Understand the idea
Each step has a job. Understanding establishes the question. Manual work gives you something concrete to inspect. A paper design turns that work into a procedure and checks its cost. Playing devil’s advocate challenges the procedure before you invest in code. Implementation expresses it clearly; motivated tests check the actual program; cleanup makes a working solution easier to read.
The order is a guide, not a promise that the first plan will work. A counterexample sends you back to design; a failed test may reveal either a coding mistake or a mistaken assumption. After cleanup, rerun the relevant tests. Explain your reasoning along the way rather than replacing the cleanup step with a final speech.
Worked example
For Two Sum, the route is: clarify positions versus values; find a pair by hand; plan a lookup of earlier values; try to make the plan reuse one position; write the function; check purposeful cases; improve local names and check again.
Try it yourself
A test fails after you rename a variable. Is the right response to invent a new algorithm?
Show a worked solution
First inspect the small change against the previously working version. A missed reference may be a coding mistake. If the test exposes a flawed plan instead, return to design. Diagnose the failure before changing more code.

Step 1 · 1 · Understand what is being asked
1 · Understand what is being asked
Read carefully, explain the task in your own words and connect each rule to a small example.
Explanation, worked example and practice
Understand the idea
Read the statement and its examples together. Pause at details that change an answer: what the output represents, whether values may repeat and whether a solution is guaranteed. If a requirement is ambiguous in an interview, ask a focused question. In independent practice, write the interpretation you will use.
Our Two Sum task is: given an integer list numbers and an integer target, return two different zero-based positions whose values add to target. Return [] if no pair exists. Any valid pair is accepted, and the input must remain unchanged. These are the rules for this lesson; other versions may choose different rules.
Worked example
For [4, 1, 6, 3] and target 9, the values 6 and 3 add to 9. They are at positions 2 and 3, so [2, 3] is an accepted output. [6, 3] would answer a different question: it contains values rather than positions.
Try it yourself
For numbers = [8, 2, 5] and target = 7, give one accepted output. Explain what the two numbers in your output represent and why they form a valid answer.
Show a worked solution
[1, 2] is accepted: these are zero-based positions in the original list, not the values being added. They are different positions, both are in range, and numbers[1] + numbers[2] = 2 + 5 = 7. [2, 1] is equally valid. Returning [2, 5] would confuse the values with positions.

Step 1 · 1 · Understand what is being asked
Clarify the cases that change the rules
A short clarification now can prevent an entire implementation of the wrong task.
Explanation, worked example and practice
Understand the idea
Distinguish repeated values from reusing a position. [3, 3] contains two elements; [3] contains one. Ask what to do when there is no pair and whether multiple answers are allowed. Record the answers beside the example instead of relying on memory.
Also identify the input assumptions. This exercise supplies integers; parsing arbitrary form input is a separate problem. Avoid silently sorting or changing numbers, because the requested positions refer to the original list.
Worked example
With target 6, [3] requires [], while [3, 3] accepts [0, 1]. For [1, 4, 2, 3], target 5, both [0, 1] and [2, 3] are accepted. A test that insists on only one of them would reject another correct answer.
Try it yourself
The interviewer says only: 'Find two numbers that sum to the target.' Write exactly two clarification questions that could change your solution or output.
Show a worked solution
1. Should I return the two values or their positions in the original list? 2. What should I return if no valid pair exists? These settle the output meaning and the no-solution result. Other useful pairs of questions could address reusing a position, equal values or multiple valid answers.

Step 2 · 2 · Solve a small input by hand
2 · Solve a small input by hand
Find an answer before choosing a data structure. Watch the work you repeat.
Explanation, worked example and practice
Understand the idea
Use a small input that you can inspect without code. Try possible pairs and write down why they succeed or fail. You are learning how you solve this instance; the next step will turn that process into a method for other inputs.
Do not start by guessing the optimized code. A straightforward manual search supplies both a baseline and expected results that you can later use to check a faster idea.
Worked example
For [4, 1, 6, 3], target 9, pair 4 with 1, 6 and 3: the sums are 5, 10 and 7. Next try 1 with 6 and 3: 7 and 4. Finally, 6 + 3 = 9, so positions [2, 3] work. Six pair checks were enough to settle this input.
Try it yourself
For [2, 4, 5] and target 6, list all three unordered pairs of different positions and calculate each pair's value sum. Then give one accepted output.
Show a worked solution
Positions (0, 1) give 2 + 4 = 6; (0, 2) give 2 + 5 = 7; (1, 2) give 4 + 5 = 9. The accepted output is [0, 1], or [1, 0]. We list every pair here to inspect this small example; a solver may stop once it finds a valid pair.

Step 2 · 2 · Solve a small input by hand
Notice the question you keep asking
For each value, ask which other value would complete the target.
Explanation, worked example and practice
Understand the idea
In the manual search, many checks answer the same kind of question: “Is the value I need somewhere else?” If the current value is value, its partner must be target - value. This does not yet choose a data structure; it identifies the repeated work that a design could improve.
Write down the complement for each element and where you found it. Keep the distinction between a value and its position visible. These notes will help you choose what information to store.
Worked example
For [4, 1, 6, 3], target 9, the needed values are 5, 8, 3 and 6. At the final 3, the needed 6 has already appeared at position 2. That suggests keeping a record of earlier values and their positions instead of scanning them again.
Try it yourself
For [2, 7], target 9, what information from the first element would help when you reach 7?
Show a worked solution
Keep both the earlier value 2 and its position 0. At 7, compute 9 - 7 = 2; the earlier record can supply position 0, giving [0, 1]. Keeping only “a previous element existed” would not answer either lookup question.

Step 3 · 3 · Put a complete solution idea on paper
3 · Put a complete solution idea on paper
Write what you store, what you look up, when you update it and when you return.
Explanation, worked example and practice
Understand the idea
Paper makes the moving parts visible and reduces how much you must hold in your head while speaking. Use a few sentences, a sketch or pseudocode. Fill the logical gaps before typing: “use a dictionary” is a tool choice, not a complete procedure.
For Two Sum, let seen map an earlier value to a position containing it. Move left to right. First look for target - value in seen. If present, return its earlier position and the current position. Otherwise record the current value and position. Return [] only after the whole loop ends.
The important rule is that a lookup sees only earlier positions. This is often called a loop invariant: a statement that stays true from one iteration to the next. Here it explains why a found pair uses different elements.
Why can this find any existing pair? For positions i < j that form a pair, reaching j without an earlier answer means the needed value from i has already been recorded. Keeping a newer earlier position for a repeated value still leaves that value available, so the lookup at j can find a valid partner.
Worked example
On [4, 1, 6, 3], target 9: before the final position, seen is {4: 0, 1: 1, 6: 2}. The current value is 3, so look for 6. Its stored position is 2; return [2, 3]. No need to store the final 3 once a pair has been found.
position | value | needed | seen before lookup | action
0 | 4 | 5 | {} | record 4:0
1 | 1 | 8 | {4:0} | record 1:1
2 | 6 | 3 | {4:0,1:1} | record 6:2
3 | 3 | 6 | {4:0,1:1,6:2} | return [2,3]Try it yourself
State the rule for seen without using the term “invariant.” What must the first lookup see?
Show a worked solution
Before checking the current element, seen contains values only from positions we have already passed. The first lookup sees an empty dictionary. Recording an element after checking it preserves this rule for the next position.

Step 3 · 3 · Put a complete solution idea on paper
Check time and space before implementing
Count the work inside helpers as well as the visible loop.
Explanation, worked example and practice
Understand the idea
The manual pair search may inspect n(n - 1)/2 pairs, so its worst-case work grows as O(n²). The dictionary design visits each position once. With expected constant-time dictionary lookup and insertion, its expected time is O(n); it may store O(n) entries. The extra memory buys less repeated searching.
A helper can hide expensive work. If each iteration builds numbers[:index] and searches that slice, copying and searching may each take linear work. Calling the code “one loop” does not make the whole algorithm linear. Include such costs when deciding whether your idea fits the problem constraints.
Worked example
At n = 20, the pair method has 190 possible unordered pairs. The dictionary design processes at most 20 positions, though the operations are different and these counts are not a timing benchmark. If memory limits rule out the dictionary, revisit the design and explain the trade-off.
Try it yourself
A helper scans all earlier values on every iteration. Can you claim O(n) time because the calling function has one for loop?
Show a worked solution
No. The scans can total 0 + 1 + ... + (n - 1), which is O(n²). Describe the helper cost and the accumulated work before making the complexity claim.

Step 4 · 4 · Try to break your idea
4 · Try to break your idea
Challenge your favourite plan before spending time implementing it.
Explanation, worked example and practice
Understand the idea
It is easy to find examples that agree with an idea you like. Instead, ask what would make it fail. Look for an assumption the problem never promised, an update in the wrong order or a return that happens too early. A small counterexample can save an entire implementation of a bad plan.
For the dictionary plan, try the smallest input that could match itself: [3], target 6. If you record the current 3 before searching, the dictionary already contains that same position. The lookup succeeds, but [0, 0] breaks the requirement to use two different elements.
Worked example
The repair is to search first and record afterward. On [3], the empty dictionary provides no partner, so the function ends with []. On [3, 3], the second 3 finds the first one and returns [0, 1]. Rejecting all equal-value pairs would hide one bug by introducing another.
Try it yourself
A proposed fix rejects every pair whose two values are equal. Give an input list and target that show why this is wrong. State the valid positions the fix would reject.
Show a worked solution
Use [3, 3] with target 6. Positions 0 and 1 are different, and their equal values sum to 6, so [0, 1] is valid. The proposed fix would reject this allowed answer. Prevent matching one position with itself by searching before recording; do not ban equal values at different positions.

Step 4 · 4 · Try to break your idea
Audit your assumptions, not just the happy path
Check order, duplicates, negative values and the moment you declare failure.
Explanation, worked example and practice
Understand the idea
Read your plan as if someone else proposed it. Does it quietly require a sorted list? Unique values? Positive numbers? Compare each assumption with the problem statement. An assumption is acceptable only when the problem grants it or you justify how you establish it.
Also inspect the unsuccessful path. Failing to find a partner for the first value does not show that later values cannot form a pair. “No solution” belongs after the loop. If a counterexample breaks the plan, return to the paper design and trace the repair before coding.
Worked example
For [1, 2, 8], target 10, the first needed value 9 is absent. Returning [] there would miss 2 + 8 at positions [1, 2]. For [-2, 7], target 5, [0, 1] is valid; a positive-values-only shortcut would need a different problem statement.
Try it yourself
Write pseudocode for the repaired Two Sum plan without copying the Python implementation. Show the starting state, lookup, recording, success return and no-pair return.
Show a worked solution
Start with an empty dictionary mapping values to earlier positions. At each position, look for target minus the current value. If it is present, return its stored position and the current position. Otherwise record the current value and position. Return [] only after the loop ends. The pseudocode below expresses that sequence.
start with an empty value-to-position dictionary
for each position and value:
look for target - value among earlier records
if found, return [earlier position, current position]
otherwise record value -> current position
return [] after the loop
Step 5 · 5 · Implement in clear, explainable blocks
5 · Implement in clear, explainable blocks
Choose a language you can use fluently, name the state clearly and keep the interviewer informed.
Explanation, worked example and practice
Understand the idea
Use a language supported by the interview setting and suited to both the task and your fluency. A convenient library is useful only if you understand its behaviour and cost. You do not need to use the same language forever, but changing to an unfamiliar one during the interview can add avoidable work.
Group the implementation into logical blocks. Use meaningful names; extract a helper when it gives a repeated operation or a complex condition a useful name. Do not split a short function merely to create more helpers. Briefly explain a completed block, and say what you are investigating if you pause. You need not narrate every keystroke.
Worked example
Before coding the lookup block, say: “seen connects an earlier value to its position. I will check for the needed value before recording this element.” After the block, explain the success return and then the final no-pair return. This communicates the decisions at the moments they matter.
Try it yourself
Which explanation helps more than reading out the line seen[value] = index?
Show a worked solution
“I record this element after the lookup, so the next lookup can use it, but this element cannot match itself.” It explains the reason for the line and connects the code to the design.

Step 5 · 5 · Implement in clear, explainable blocks
Translate the plan into a small working function
Keep the search-before-record order visible in the code.
Explanation, worked example and practice
Understand the idea
This exercise changes one line in a working implementation so you can explain the resulting failure. Next you will choose your own tests, then inspect how a checker judges their results. Keep the prediction separate from what a run actually reaches.
enumerate(numbers) gives each position together with its value. needed in seen checks whether a matching value was recorded earlier; seen[needed] retrieves its position. Once a valid pair is found, return immediately. The final [] handles the input with no pair.
To run this complete block, save it as two_sum.py and use python3 two_sum.py, or py two_sum.py on Windows. It prints “Three checks passed.” after the assertions succeed. If an assertion fails, Python stops with AssertionError. The examples assume Python 3 is already installed.
Worked example
Follow the implementation on [3, 3], target 6. The first lookup fails and stores 3: 0. The second lookup finds that record and returns [0, 1]. The input list is read but not changed.
def two_sum(numbers, target):
seen = {}
for index, value in enumerate(numbers):
needed = target - value
if needed in seen:
return [seen[needed], index]
seen[value] = index
return []
assert two_sum([4, 1, 6, 3], 9) == [2, 3]
assert two_sum([3], 6) == []
assert two_sum([3, 3], 6) == [0, 1]
print("Three checks passed.")Try it yourself
Run the original block. In a copy, move seen[value] = index to immediately before if needed in seen, removing its old occurrence; change nothing else. Predict pass or fail for each of the three checks, then run the copy. Explain where execution stops. Restore the original order and rerun. Report actual output separately from your predictions, or say if you could not run it.
Show a worked solution
In the altered function, the normal [4, 1, 6, 3], target 9 check still passes. The [3], target 6 check fails because the first element now finds itself and returns [0, 0] instead of []. The [3, 3], target 6 check would also fail with [0, 0], before reaching the second element.
The supplied script stops at the first failing assertion, which is the [3] check; it does not reach the duplicate-values check in that run. That third result is a prediction unless tested separately. After restoring the original order, the expected final message is 'Three checks passed.' Record your own observed result, or state that it was not run.

Step 6 · 6 · Give every test a reason
6 · Give every test a reason
Choose your own inputs to catch a specific mistake, and calculate the correct result before running them.
Explanation, worked example and practice
Understand the idea
After implementation, test without waiting for the interviewer to prompt you. Choose each case for a reason: one element for self-matching, equal values at different positions for duplicates, a late pair for premature return, negative values for a hidden sign assumption and empty input for a loop that never runs.
Check the question the program was asked. With multiple valid pairs, validate the returned positions rather than demanding your favourite answer. Also check that the input stayed unchanged. Expected results should come from manual reasoning or a simpler independent method, not from copying the implementation into the test.
Worked example
For [1, 4, 2, 3], target 5, both [0, 1] and [2, 3] pass. A returned pair must contain two distinct in-range positions whose values sum to 5. For [1, 2], target 8, the required no-solution output is the list [], not None or an empty tuple.
Try it yourself
Choose two Two Sum tests: one that exposes reusing a single position, and a similar one where equal values at two different positions must be allowed. Give each input, target, expected result and purpose. Expected results describe the correct behavior; both tests may fail on the same faulty implementation.
Show a worked solution
Test 1: [3], target 6, must return []; its purpose is to catch a false [0, 0] answer that reuses the only position. Test 2: [3, 3], target 6, accepts [0, 1] or [1, 0]; its purpose is to allow equal values from different positions. A save-before-search implementation fails both by returning [0, 0]. The second test is a legitimate pair, not a promise that the broken code passes it.

Step 6 · 6 · Give every test a reason
Run checks that accept every valid answer
Extended checker exercise: decide whether a result satisfies the rules, even when several pairs are valid.
Explanation, worked example and practice
Understand the idea
This complete program combines the solver, a small result checker and eight purposeful cases. The checker first enforces the declared output form. For [], it checks that no pair exists using a straightforward pair search. For a nonempty answer, it checks integer positions, bounds, distinctness and the sum.
Save it as check_two_sum.py and run python3 check_two_sum.py, or py check_two_sum.py on Windows. The reference search is deliberately simple: the test inputs are tiny, so readability matters more than its speed. Passing these checks is evidence about these cases; the earlier design reasoning explains why the algorithm should work generally.
You are ready to continue when you can reject a reused position, accept a different valid pair and justify an empty result. Use the eight-case exercise to check those decisions. You can revisit the checker’s implementation later; you do not need to memorize it before continuing.
Worked example
The last three assertions inspect the checker itself: it must reject self-matching and reject None or () as a replacement for []. This avoids a truthiness check accidentally accepting any false-like value when no solution exists.
def two_sum(numbers, target):
seen = {}
for index, value in enumerate(numbers):
needed = target - value
if needed in seen:
return [seen[needed], index]
seen[value] = index
return []
def has_pair(numbers, target):
return any(numbers[i] + numbers[j] == target
for i in range(len(numbers))
for j in range(i + 1, len(numbers)))
def valid_result(numbers, target, result):
if not isinstance(result, list):
return False
if result == []:
return not has_pair(numbers, target)
if len(result) != 2:
return False
i, j = result
if type(i) is not int or type(j) is not int:
return False
return (0 <= i < len(numbers) and 0 <= j < len(numbers)
and i != j and numbers[i] + numbers[j] == target)
cases = [
([4, 1, 6, 3], 9), # positions, not values
([3], 6), # cannot reuse one position
([3, 3], 6), # equal values at different positions
([-2, 7], 5), # negative value
([], 0), # empty input
([1, 2, 8], 10), # do not return too early
([1, 4, 2, 3], 5), # more than one accepted pair
([1, 2], 8), # no solution
]
for numbers, target in cases:
before = numbers.copy()
result = two_sum(numbers, target)
assert numbers == before
assert valid_result(numbers, target, result)
assert not valid_result([3], 6, [0, 0])
assert not valid_result([1, 2], 8, None)
assert not valid_result([1, 2], 8, ())
print("Eight cases and three checker checks passed.")Try it yourself
Suppose the solver always returns []. For each of the eight cases in the program, predict whether the checker accepts or rejects that result, and explain the distinction. You can reason without running it; if you run the original test loop, remember it stops at the first failing assertion.
Show a worked solution
The checker rejects [] on five cases that contain a pair: [4, 1, 6, 3], target 9; [3, 3], target 6; [-2, 7], target 5; [1, 2, 8], target 10; and [1, 4, 2, 3], target 5. It accepts [] on the three genuinely pair-free cases: [3], target 6; [], target 0; and [1, 2], target 8. An always-empty solver therefore cannot pass the full suite. In the supplied order, execution would stop at the first case; the remaining outcomes are predictions unless checked separately.

Step 7 · 7 · Simplify and clean up the code
7 · Simplify and clean up the code
When the solution works, use the remaining time to make it easier to read and check.
Explanation, worked example and practice
Understand the idea
Look at the working code as your next reader would. Can the names explain what each value means? Is there a repeated or complicated operation that would benefit from a helper? Would one short comment explain an important decision? Preserve the function’s required interface and behaviour while improving its presentation.
Cleanup is optional when time is tight; checking correctness and explaining unfinished work take priority. Keep the changes small. A large late rewrite creates new risk and gives you less time to check it. After any change, rerun the relevant tests.
Worked example
In the same function, local names d, i, x and y can become seen, index, value and needed. Keep the function name and its numbers and target parameters unchanged. A comment about searching before recording is useful; a comment saying “add one to i” would only repeat obvious code.
Try it yourself
Would extracting needed = target - value into its own helper improve this short function? Explain your decision.
Show a worked solution
Usually it would add a jump for a simple expression without clarifying a repeated or complex operation. Keep it inline here. Helpers are useful when the boundary they introduce helps the reader, not simply because a line can be moved.

Step 7 · 7 · Simplify and clean up the code
Refactor a working version, then check it again
A cleanup should improve the names without changing which inputs and outputs are accepted.
Explanation, worked example and practice
Understand the idea
The version below implements the same algorithm with short local names. Rename those locals and keep the ordering, return conditions and function signature. Compare the result with your paper plan rather than assuming a cosmetic change is harmless.
Then put the cleaned function into the complete checker from the testing step and run it again. Tests can catch a missed name or moved assignment. The invariant still matters: every stored position must precede the position being checked.
Worked example
The answer provides the cleaned function. Notice that the algorithm and public parameters stay the same. The improvement is that a reader can tell what is stored and what is needed without mentally decoding single-letter names.
def two_sum(numbers, target):
d = {}
for i, x in enumerate(numbers):
y = target - x
if y in d:
return [d[y], i]
d[x] = i
return []Try it yourself
Rewrite the displayed function with clearer local names while preserving its signature and behavior. Replace only the solver in unit 14's eight-case checker and rerun it if you can. Submit your function, name one preserved behavior, and report the observed output or explicitly say it was not run.
Show a worked solution
The function below renames d, i, x and y to seen, index, value and needed. It preserves search before recording; for example [3], target 6 still returns []. Replacing only the solver in unit 14 leaves the expected final message 'Eight cases and three checker checks passed.' This is the expected outcome; report your own observed output separately, or state that you did not run it.
def two_sum(numbers, target):
seen = {}
for index, value in enumerate(numbers):
needed = target - value
if needed in seen:
return [seen[needed], index]
seen[value] = index
return []
Longer practice: apply the seven steps to image smoothing
Longer practice: apply the seven steps to image smoothing
Allow more time for this transfer task. Complete the paper design first, then implement and check it.
Explanation, worked example and practice
Understand the idea
Problem: given a rectangular grid of nonnegative integer brightness values, produce a new grid. For each output cell, take the input cell at the same position and its existing neighbours, including diagonals, and round their average down. Ignore locations outside the grid; keep the input unchanged. Empty input returns []; ragged rows are rejected.
Work in three sittings if useful: paper design, implementation, then verification and cleanup. First restate what a corner may read, calculate the corner and centre by hand, decide where old and new values live, and challenge a tempting shortcut. Write that design before opening the answer. Then implement it, choose motivated checks, and clean up and rerun. The stages follow the same seven steps; the grid adds more boundary decisions than Two Sum.
For [[0, 0, 0], [0, 9, 0], [0, 0, 0]], begin with the top-left corner and the centre. Do not assume that every neighbourhood contains nine cells. Also ask what later cells would read if you overwrote the input while scanning.
Worked example
First manual checks: the top-left corner sees four values totalling 9, so 9 // 4 = 2. The centre sees nine values totalling 9, so 9 // 9 = 1. These give expected results before you have an implementation.
Try it yourself
For the brightness grid above, work in three stages. (1) Describe where you read neighbors and write results; give a counterexample to always dividing by nine or to updating in place. (2) Implement smooth_image(grid), preserving the input and raising ValueError for unequal row lengths. (3) Give expected results for [] and [[7]], explain time and output-space costs, and run the supplied checks if able. Report observed results separately, or say not run.
Show a worked solution
Design: read neighbors from the original grid and write to a separate output grid. Reject unequal row lengths with ValueError before processing cells. For each cell, try row and column offsets -1, 0 and 1; include only in-bounds positions, count them and round total / count down.
Counterexample: the shown top-left corner has four values totaling 9, so its result is 9 // 4 = 2. Always dividing by nine would wrongly give 1. Checks: [] returns []; [[7]] returns [[7]]; the full example returns [[2, 1, 2], [1, 1, 1], [2, 1, 2]]. Compare the original grid with a saved copy, and check that [[1, 2], [3]] raises ValueError.
For a grid with rows rows and a positive number cols of columns, at most nine neighbors are inspected per cell, so time and output space are O(rows × cols). Each processed neighborhood includes its own cell, so its count is positive. The implementation below reads the original data and creates separate output rows. Save the complete block as image_smoother.py and run python3 image_smoother.py, or py image_smoother.py on Windows. Its expected final message is 'Image checks passed.' Record your actual result or mark it not run; after cleanup, rerun the affected checks.
def smooth_image(grid):
if not grid:
return []
rows, cols = len(grid), len(grid[0])
if any(len(row) != cols for row in grid):
raise ValueError("grid must be rectangular")
result = [[0] * cols for _ in range(rows)]
for row in range(rows):
for col in range(cols):
total = count = 0
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
r, c = row + dr, col + dc
if 0 <= r < rows and 0 <= c < cols:
total += grid[r][c]
count += 1
result[row][col] = total // count
return result
original = [[0, 0, 0], [0, 9, 0], [0, 0, 0]]
saved = [row[:] for row in original]
assert smooth_image(original) == [[2, 1, 2], [1, 1, 1], [2, 1, 2]]
assert original == saved
assert smooth_image([]) == []
assert smooth_image([[7]]) == [[7]]
try:
smooth_image([[1, 2], [3]])
except ValueError:
pass
else:
raise AssertionError("ragged input must be rejected")
print("Image checks passed.")
Longer practice: apply the seven steps to image smoothing
Practise the process until you can retrieve it
Understand. Solve manually. Design on paper. Challenge. Implement. Test. Simplify and clean up.
Explanation, worked example and practice
Understand the idea
After practising, review how you reached a solution rather than only whether it was accepted. Did you clarify the output? Did the manual work lead to the design? Did you challenge an assumption? Did each test have a purpose? Did you communicate the important decisions and recheck cleanup?
Take this checklist to the next practice problem. Start with enough time to work through the steps deliberately; as the routine becomes familiar, practise explaining the same decisions under interview conditions. Keep cleanup when time allows and return to an earlier step when evidence demands it.
Worked example
For Two Sum, a concise account is: I need distinct original positions; manual pairs reveal repeated lookup work; a dictionary stores earlier values and positions; [3] challenges update order; the code searches before recording; tests cover duplicates, no pair and late success; cleanup improves local names and is followed by a rerun.
Try it yourself
A new task asks for the original position of a specified value. On [8, 2, 5], find 8. A proposed plan sorts first and returns position 2. How would you investigate it with the playbook?
Show a worked solution
First clarify that the position refers to the original list: the manual answer is 0. Trace the sorting step; it changes positions, so the plan answers a different question. Revise the design before implementation, choose a case whose order changes, and retest. A shorter or cleaner implementation cannot repair the wrong interpretation of the task.
Quote of the day
What I cannot create, I do not understand.
Was this lesson useful?
Leave a like, or share it with someone who could use it.
Hear about new articles and lessons