How to Solve Any Problem
The 6-step method
- Understand: repeat the problem in your own words. Ask about input size, negatives, duplicates, empty input, and what to return.
- Examples: work through a normal case and an edge case by hand.
- Brute force: say the simplest correct idea and its Big O, even if it's slow.
- Optimise: look for a pattern (table below) and explain the improvement.
- Code: clean names, small helper functions, and talk as you write.
- Test: run your examples through the code, then check edge cases and state the time and space complexity.
Pattern finder
| If the problem mentions… | Try |
|---|---|
| sorted array, "find" | binary search, two pointers |
| pairs or sums, "seen before" | hash map |
| contiguous subarray or substring | sliding window, prefix sums |
| K largest or smallest, streaming | heap |
| brackets, "next greater" | stack |
| levels, shortest steps | BFS |
| all combinations or permutations | backtracking |
| "number of ways", min or max cost | dynamic programming |
| intervals, scheduling | sort + greedy |
| dependencies, ordering | topological sort |
| linked list cycle or middle | fast and slow pointers |
Communication tips
- Think out loud; silence makes it hard for the interviewer to help.
- If stuck, solve a smaller version, or ask for a hint; that's allowed.
- Mention trade-offs: "This uses O(n) extra memory to get O(n) time."
Example
# Applying the method to "Two Sum"
# 1. Understand: return indexes of two numbers adding to target.
# 2. Example: [2, 7, 11, 15], target 9 → (0, 1)
def two_sum_brute(nums, target): # 3. Brute force: O(n²)
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 two_sum(nums, target): # 4. Optimised: O(n) with a hash map
seen = {}
for i, x in enumerate(nums):
if target - x in seen:
return seen[target - x], i
seen[x] = i
return None
# 6. Test: normal, duplicates, no answer, empty
tests = [([2, 7, 11, 15], 9), ([3, 3], 6), ([1, 2], 10), ([], 1)]
for nums, target in tests:
print(nums, target, "→", two_sum(nums, target))
# Time O(n), space O(n)