Data Structures & Algorithms · Module 13 · Lesson 11 min read

How to Solve Any Problem

The 6-step method

  1. Understand: repeat the problem in your own words. Ask about input size, negatives, duplicates, empty input, and what to return.
  2. Examples: work through a normal case and an edge case by hand.
  3. Brute force: say the simplest correct idea and its Big O, even if it's slow.
  4. Optimise: look for a pattern (table below) and explain the improvement.
  5. Code: clean names, small helper functions, and talk as you write.
  6. 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 substringsliding window, prefix sums
K largest or smallest, streamingheap
brackets, "next greater"stack
levels, shortest stepsBFS
all combinations or permutationsbacktracking
"number of ways", min or max costdynamic programming
intervals, schedulingsort + greedy
dependencies, orderingtopological sort
linked list cycle or middlefast 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

Python
# 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)