Python Course · Problem-solving method
How to Solve Python Algorithm Problems Step by Step
Learn a repeatable Python interview method through two-sum: clarify, brute force, optimize, test and explain.
Learn the pattern, trace runnable code, and test an edge case.
Core idea
Make the contract and invariant visible before optimizing.
Find repeated work
Optimize + test
The direct answer
Develop a correct answer before making it faster.
The hardest part of many Python algorithm questions is not typing code; it is deciding exactly what the function must return and why an optimization remains correct. This lesson develops two-sum from a nested-loop baseline to a dictionary solution, with constraints, tests and complexity.
The example uses a list of integers and asks for two distinct indices whose values add to a target. The code returns None when no pair exists. Python’s data-structures tutorial covers dictionaries; the course pricing block follows this introduction.
Course access
Choose your next step in Python.
Review the current course options and access details here.
Heycademy Courses · Coming Soon
Master Python with Heycademy
We’re preparing an interactive learning experience with practical exercises, skill assessments and personalized learning to help you build confidence and master new skills.
We’re putting the finishing touches on this course. Please check back for updates.
Clarify the problem
Define indices, ties and no-solution behavior.
| Question | Chosen contract |
|---|---|
| Input | A list of integers and an integer target. |
| Output | Tuple (earlier index, current index) for first pair found while scanning left to right. |
| Same position twice? | Not allowed. |
| Duplicates? | Allowed; two equal values may form a pair. |
| No pair? | Return None. |
| Mutation? | Do not change input. |
Without this contract, two implementations may both be “correct” under different interpretations. An employer might specify a unique solution, any valid pair or one-based indices. Restate the actual question before coding. Here the first pair found by a left-to-right scan is deterministic.
Correct baseline
Try every earlier pair once.
def two_sum_brute(values, target):
for right in range(len(values)):
for left in range(right):
if values[left] + values[right] == target:
return (left, right)
return NoneFor [2, 7, 11, 15] and target 9, right index 1 compares with left index 0 and returns (0,1). For [3,3] and target 6, it also returns (0,1), never reusing one element. The nested loops can examine O(n²) pairs and use O(1) auxiliary space.
The baseline is worth writing because it establishes correctness and a benchmark. Do not jump to a dictionary before explaining which work is repeated: the inner loop searches earlier values for the needed complement on every right index.
Replace repeated search
Map earlier values to their indices.
def two_sum_indices(values, target):
seen = {}
for index, value in enumerate(values):
complement = target - value
if complement in seen:
return (seen[complement], index)
seen[value] = index
return NoneBefore processing index i, seen contains values at earlier indices. The needed earlier value is target - values[i]. Check it before inserting the current value, ensuring a single position cannot pair with itself. Expected time is O(n) under average dictionary lookup, with O(n) auxiliary space.
| Index | Value | Complement | seen before check | Decision |
|---|---|---|---|---|
| 0 | 3 | 3 | {} | Store 3→0. |
| 1 | 3 | 3 | {3:0} | Return (0,1). |
Storing before checking would incorrectly let the first 3 pair with itself for target 6. The ordering of those two lines is part of the proof, not an incidental coding style.
Keep building this skill
Turn the example into a tested solution.
Return to the course options whenever you are ready.
Normal and boundary tests
A sample, a duplicate and no solution.
assert two_sum_indices([2, 7, 11, 15], 9) == (0, 1)
assert two_sum_indices([3, 3], 6) == (0, 1)
assert two_sum_indices([1, 2], 9) is None
assert two_sum_indices([], 0) is NoneThese checks target distinct failure modes. The duplicate test catches self-reuse or lost earlier index. The no-pair and empty tests exercise the documented None return. Add a negative-value case such as [-2, 5, 7] with target 3, expecting (0,1). A dictionary key can be negative, so the method still applies.
Unseen transfer
Change the output requirement first.
Suppose the interviewer now asks for all distinct index pairs, not the first pair. The function above stops early and is no longer sufficient. You would need a data structure that retains multiple earlier indices per value and an output policy that avoids duplicate pairs. If the number of valid pairs is large, output size itself becomes part of complexity.
What if input values are floats?
The dictionary approach can run with hashable floats, but exact equality and rounding semantics may make a mathematically expected pair unreliable. Clarify numerical tolerance and representation before promising exact matches.
Another change asks for sorted value pairs rather than indices. Sorting may be a useful two-pointer approach, but it changes how original indices are handled. The new contract drives the new algorithm.
Interview explanation
Name invariant, tradeoff and limit.
A concise explanation is: “I scan left to right. Before each position, the map contains values from earlier positions and their indices. If the needed complement is present, I have a valid distinct pair. Otherwise I store the current value. This takes expected O(n) time and O(n) space.” That is more persuasive than “I used a hashmap because two-sum uses one.”
Practice with the 20-problem page and classify when a different pattern is justified. The method—contract, baseline, repeated work, invariant, tests—transfers well beyond two-sum.
Trace a changed two-sum case
Negative values do not break the map.
Input [-2, 5, 7], target 3. At index 0, value -2 needs complement 5; the map is empty, so store -2→0. At index 1, value 5 needs -2; the map contains it, so return (0,1). The algorithm does not require nonnegative numbers. It requires arithmetic-compatible, hashable values under the chosen equality semantics.
| Index | Value | Needed earlier value | Map before | Action |
|---|---|---|---|---|
| 0 | -2 | 5 | {} | Store -2→0. |
| 1 | 5 | -2 | {-2:0} | Return (0,1). |
Contrast this with the subset-sum lesson, whose bounded pruning explicitly requires nonnegative integers. The same input property can be irrelevant to one algorithm and essential to another. State assumptions for the particular proof, not for Python in general.
Wrong repairs
Avoid changing the task while optimizing it.
Sorting the input can make a two-pointer solution possible, but it changes original index positions unless you carry them along. Returning the values (2,7) instead of indices (0,1) violates this lesson’s contract. Storing the current value before checking the complement can reuse one index for target twice that value. Overwriting a prior index may also change which valid pair is returned when several exist.
When a test fails, compare the result with the exact contract before editing the algorithm. If the interviewer changes “first pair encountered” to “any pair,” some tie behavior becomes flexible. If the interviewer changes to “all pairs,” early return is no longer valid. This is why clarification is part of problem solving, not a preamble to skip.
Prove the map contains only earlier positions
Test the order of two lines.
The optimized two-sum implementation checks for the complement before storing the current value. At index i, every index in the map is less than i. That is the invariant. Suppose the list is [3] and the target is 6. Checking before storing finds no earlier 3 and returns None, correctly refusing to reuse the same position. Storing first would put 3→0 into the map, then find it and return (0,0), an invalid pair under the stated contract.
| Input | Correct output | Buggy store-first output |
|---|---|---|
| [3], target 6 | None | (0,0) |
| [3,3], target 6 | (0,1) | (0,0) at first item |
| [], target 0 | None | None |
The one-element test is more diagnostic than a long random list because it isolates self-reuse. Keep it in the test suite. This also demonstrates why a correctness proof can guide test selection: the test challenges exactly the invariant you claim.
FAQ
Questions about this skill.
Why check before storing?
It prevents pairing an element with itself.
Is the dictionary method always O(n)?
O(n) expected under average hashing; worst-case hashing assumptions differ.
Should I always optimize immediately?
First establish the contract and a correct baseline, then use constraints to justify optimization.
Continue with the course
Build reliable Python interview skills.
Review the course options and choose your next learning step.