Lesson 37/48 ยท ๐ŸŽฏ Problem Solving
๐ŸŽฏ Problem SolvingLesson 37/48
Phase 6 ยท Problem Solving30 min

Brute Force First, Always

The most important rule: solve it simply first, optimise later

Brute force means the simplest possible approach, even if it's slow. Check every option. Try every combination. Who cares if it's inefficient?
The rule is: Make it work first. Then make it fast.
This isn't laziness, it's wisdom. A working slow solution is infinitely better than a broken fast one.
Problem: Find two numbers that sum to targetpython
# Brute force: check every pair
def two_sum_brute(numbers, target):
    n = len(numbers)
    for i in range(n):
        for j in range(i + 1, n):        # every pair
            if numbers[i] + numbers[j] == target:
                return [i, j]
    return []

# Works! O(nยฒ) time, checks every pair
Then think: "Can I do better?" The brute force is O(nยฒ), for 1000 numbers, that's 1 million checks. A smarter approach using a dictionary does it in O(n), 1000 checks. But you need the brute force to understand the problem first.
Optimised version (after you understand it)python
def two_sum_fast(numbers, target):
    seen = {}                    # dict: value โ†’ index
    for i, num in enumerate(numbers):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []
In an interview, always say "I'll start with the brute force to make sure I understand the problem, then optimise." Interviewers love this, it shows systematic thinking.

Practice Exercises

0/2 solved
Exercise 1 of 2medium
โฑ 00:00

Two Sum

Write a function two_sum(numbers, target) that returns the indices of two numbers that add up to target.
You can assume exactly one solution exists. Return as a list [i, j] where i < j.
Start with the brute force approach!
solution.py
1 / 2
Exercise 2 of 2easy
โฑ 00:00

Contains Duplicate

Write a function has_duplicate(numbers) that returns True if any number appears more than once.
First write the brute force (O(nยฒ)), then try to think of a faster way.
solution.py
2 / 2
Solve all 2 exercises to unlock completion