Sub topic 5
Will It Run in Time? Estimating Brute-Force Cost
This chapter assumes you can read Big-O notation and write nested loops in Python. It also assumes you have seen the two-sum brute force from the earlier chapters. You now have a correct, obviously right solution. The next question is whether it finishes within the time you have, before you spend any effort optimizing it.
The Core Formula
A brute-force solution's running time comes from two numbers:
- Candidate count: how many items the search space contains.
- Work per candidate: how many steps it takes to build and check one item.
Total cost ≈ candidate count × work per candidate.
For two-sum, the candidates are pairs (i, j) with i < j. There are n(n−1)/2 of them, and each check is one addition and one comparison. That makes the cost about n²/2, which is O(n²). Later chapters enumerate subsets, with 2ⁿ candidates, and orderings, with n! candidates. The same formula applies to them.
The Operation Budget
To compare an estimate with a time limit, you need a rough rate. A plain Python loop with a small body runs a few million to about ten million iterations per second. Compiled languages such as C++ or Java run roughly 10⁸ simple operations per second. These are orders of magnitude, not guarantees, but they are accurate enough for a go/no-go decision.
For a one-second budget in Python, the largest n you can handle is roughly:
| Complexity | Typical brute force | Largest n (Python, ~1 s) |
|---|---|---|
| O(n²) | all pairs | about 3,000 |
| O(n³) | all triples | about 200 |
| O(2ⁿ · n) | all subsets, summing each | about 20 |
| O(n! · n) | all orderings, scoring each | about 9 |
You can read the table in reverse. When a problem states "n ≤ 20", the author is hinting that an exponential search over subsets is expected. When it states "n ≤ 10⁵", any quadratic approach is ruled out.
Measure to Check Your Estimate
Back up the arithmetic with a quick experiment. Use worst-case input, where no answer exists, so the function cannot return early:
import time
def two_sum_brute(nums, target):
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 time_worst_case(n):
nums = list(range(n))
target = -1 # no two non-negative numbers sum to -1
start = time.perf_counter()
two_sum_brute(nums, target)
return time.perf_counter() - start
for n in [500, 1000, 2000, 4000]:
pairs = n * (n - 1) // 2
print(f"n={n:5d} pairs={pairs:9d} seconds={time_worst_case(n):.3f}")Each time n doubles, the time should roughly quadruple. That ratio confirms the O(n²) estimate. Divide pairs by seconds to get the operation rate of your own machine.
Common Estimation Errors
- Ignoring hidden work per candidate. A call like
sum(items[i] for i in ...)inside a subset loop adds a factor of n. A list slice orincheck on a list inside a loop does the same. - Forgetting multiple test cases. If the input holds T test cases, multiply the cost by T, or use the stated limit on total input size.
- Treating constants as free. Python's per-operation cost is about 10 to 50 times higher than C++'s. An estimate that "fits in C++" can time out in Python.
- Counting the wrong thing. For n! orderings, building each permutation and scoring its n edges costs O(n) per candidate, not O(1).
Exercise
A problem asks whether any three distinct elements of an array sum to zero, with n ≤ 1,000. Estimate the brute-force cost and decide whether it fits a one-second limit in Python.
Show answer
There are n(n−1)(n−2)/6 ≈ 1.7 × 10⁸ triples, each needing a constant-time check. At a few million to ten million operations per second in Python, that takes roughly 17 to 60 seconds, which is too slow. In C++, at about 10⁸ operations per second, it would take about 2 seconds, which is borderline.
Exercise
A subset brute force builds each subset's sum with a fresh loop over all n items. For n = 25, how many operations is that, and what change would reduce it?
Show answer
There are 2²⁵ ≈ 3.4 × 10⁷ subsets, each summed in 25 steps, for about 8.4 × 10⁸ operations. That is far too slow in Python. Pruning branches, or reusing partial sums so that you don't recompute each total from scratch, cuts the work per candidate. Later chapters cover both techniques.