Sub topic 5
Will It Run in Time? Estimating Brute-Force Cost
This chapter assumes you can write loops and recursion in Python, know basic Big-O notation, and have already defined a search space and written the nested-loop two-sum solution from earlier chapters. The aim here is a habit you can apply before writing any code. Multiply a few numbers, compare the result to the input limits, and decide whether brute force will finish in time.
The Core Formula
Every brute-force solution generates candidates and checks each one. Its running time comes down to one product:
total work ≈ (number of candidates) × (cost to build and check one candidate) × (number of test cases)
Each factor has its own common mistakes, so treat them separately.
- Number of candidates is the size of the search space. For pairs from
nitems it isn(n-1)/2. For subsets it is2^n. For orderings it isn!. - Cost per candidate is the work spent building one candidate and testing it. Comparing two numbers costs O(1). Summing the chosen items of a subset costs O(n).
- Number of test cases matters when one run processes many inputs. Judges and batch jobs often state a limit on the total input size across all cases, and you should use that total.
Once you have the product, compare it to the speed of your machine and language.
How Fast Is One "Operation"?
A useful rule of thumb is that compiled languages such as C++, Rust, or Java run on the order of 10^8 simple operations per second. Pure Python runs roughly 10^7 simple loop iterations per second, sometimes a few times more. These figures are rough by design. You only need the right power of ten, because the gap between brute force and a fast algorithm is usually several powers of ten.
Measure your own rate instead of trusting the rule. The script below runs the brute-force two-sum on inputs that have no valid pair, which forces it to check every pair:
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
for n in [500, 1000, 2000, 4000]:
nums = list(range(n)) # all values >= 0
start = time.perf_counter()
result = two_sum_brute(nums, -1) # no pair sums to -1: worst case
elapsed = time.perf_counter() - start
pairs = n * (n - 1) // 2
print(f"n={n:5d} pairs={pairs:>9,d} time={elapsed:.3f}s "
f"rate={pairs / elapsed:,.0f} pairs/s result={result}")When n doubles, the time should roughly quadruple, and the rate column should stay about the same. That steady rate is your machine's cost per candidate for this loop. Divide any predicted candidate count by it to get a time estimate.
Translating Input Limits into Allowed Complexity
Problem statements, API contracts, and product requirements usually give a maximum input size. Read that limit as a hint about which complexities are acceptable. The table assumes a budget of about one second.
| Complexity | Typical brute force | Max n (compiled) | Max n (pure Python) |
|---|---|---|---|
| O(n) | single scan | ~10^8 | ~10^7 |
| O(n log n) | sort then scan | ~5×10^6 | ~5×10^5 |
| O(n^2) | all pairs | ~10^4 | ~3×10^3 |
| O(n^3) | all triples | ~500 | ~200 |
| O(n · 2^n) | all subsets, O(n) check each | ~23 | ~20 |
| O(n · n!) | all orderings, O(n) check each | ~11 | ~9 |
The rows for small n give you a clue. A limit like n ≤ 20 signals that the author expects exponential enumeration over subsets. A limit like n ≤ 10 points toward permutations. A limit like n ≤ 2×10^5 rules out anything quadratic.
Worked Estimates
Two-sum with pairs
The nested-loop solution checks n(n-1)/2 pairs at O(1) each.
- With
n ≤ 1,000, that is about 5×10^5 checks. Python finishes in well under a second. - With
n ≤ 10,000, it is about 5×10^7 checks. Python takes a few seconds. A compiled language is fine. - With
n ≤ 200,000, it is about 2×10^10 checks. Every language is too slow. This is the signal to look for the O(n) dictionary approach covered in a later chapter.
Subsets with bitmasks
The bitmask subset-sum function loops over 2^n masks, and for each mask it scans all n bits to build the sum:
def subset_sum_exists(items, target):
n = len(items)
for mask in range(1 << n):
total = sum(items[i] for i in range(n) if (mask >> i) & 1)
if total == target:
return True
return False
print(subset_sum_exists([3, 34, 4, 12, 5, 2], 9)) # True (4 + 5)
print(subset_sum_exists([3, 34, 4, 12, 5, 2], 30)) # FalseThe total is n · 2^n. At n = 20 that is about 2×10^7, which takes a few seconds in Python. At n = 30 it is about 3×10^10, far beyond any budget. Each extra item doubles the work, so the limit climbs only by one or two when you switch to a faster language or machine.
Orderings with permutations
A traveling-salesman brute force fixes city 0 as the start and tries every ordering of the rest. That is (n-1)! routes, each costing O(n) to sum. At n = 11 the count is 10! × 11 ≈ 4×10^7. At n = 13 it is 12! × 13 ≈ 6×10^9. Two extra cities multiplied the work by about 150.
Common Estimation Errors
Hidden linear costs inside the loop
Many Python operations that look atomic are O(n). Put one inside a nested loop and your complexity grows by a factor of n.
| Looks like O(1) | Actually costs | Fix |
|---|---|---|
| `x in some_list` | O(n) | use a `set` or `dict` |
| `nums[i:j]` slicing | O(j − i) copy | use indices |
| `s = s + ch` in a loop | O(len(s)) per step | collect in a list, then `"".join` |
| `sum(nums[i:j])` per pair | O(j − i) | precomputed prefix sums |
| `sorted(...)` inside a loop | O(n log n) | sort once outside |
| `list.pop(0)` or `insert(0, x)` | O(n) | `collections.deque` |
Here is a version of the pair loop that hides an extra factor of n. It tests whether every pair sum appears in the array:
def pair_sums_present_slow(nums):
count = 0
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] in nums: # O(n) list scan: total O(n^3)
count += 1
return count
def pair_sums_present(nums):
values = set(nums) # built once, O(n)
count = 0
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] in values: # O(1) expected: total O(n^2)
count += 1
return count
data = [1, 2, 3, 4, 5, 6]
assert pair_sums_present_slow(data) == pair_sums_present(data)
print(pair_sums_present(data)) # 9Both functions use the same search space and return the same answer. The only difference is the cost per candidate.
Estimating on typical inputs instead of the worst case
A brute force that returns early can look fast on random data because it often finds an answer quickly. Deadlines are set by the worst case. Build an adversarial input on purpose: one with no valid answer, or one where the answer is the last candidate checked.
Forgetting the test-case multiplier
An O(n^2) solution with n ≤ 1,000 looks safe. If the input contains up to 10^4 test cases, each with n up to 1,000, the true total is 10^4 × 5×10^5 = 5×10^9. Look for a statement such as "the sum of n over all test cases does not exceed 10^5". If it is there, it bounds the total. If it is not, multiply.
Ignoring memory
Generating every candidate into a list before checking any of them changes the memory cost. list(itertools.permutations(range(12))) tries to hold about 4.8×10^8 tuples and will exhaust memory long before time becomes the issue. Iterate lazily with a loop over the generator, or check each candidate as soon as you build it.
Reading the Estimate as a Signal
The estimate tells you which way to go next, and there are three outcomes.
- Far under budget. Brute force is a legitimate final answer. A later chapter covers when shipping it is the right call.
- Near the budget. Measure. Trim constant factors, such as hidden linear costs, needless allocation, and repeated conversions, before you redesign the algorithm.
- Far over budget. No micro-optimization will close a gap of 10^3 or more. You need a smaller search space or less work per candidate. The cost formula shows where to look: either cut the number of candidates (pruning, symmetry) or cut the cost of checking each one (hashing, prefix sums, memoization).
Even when the brute force is too slow, keep it. It is still a correct reference implementation, and later chapters use it as an oracle for testing faster code.
Exercise
A problem gives n ≤ 5,000 and a single test case. Your brute force checks all triples (i < j < k) with an O(1) test each. Estimate the number of checks and say whether it fits in one second in Python and in C++.
Show answer
The number of triples is n(n-1)(n-2)/6 ≈ 5000^3 / 6 ≈ 2.1×10^10. That is far over budget in both languages: about 2,000 seconds in Python at 10^7 per second and about 200 seconds in C++ at 10^8 per second. You need an algorithm with fewer candidates or cheaper checks, for example O(n^2) by sorting and using two pointers or a hash set.
Exercise
A function loops over all 2^n subsets of n items. For each subset it builds a Python list of the chosen items and then checks if total in forbidden_list, where forbidden_list has m entries. Write the total complexity, then name two changes that lower the cost per candidate.
Show answer
Building the list costs O(n) per subset and the list membership test costs O(m), so the total is O(2^n · (n + m)). First, make forbidden a set so the check is O(1) expected. Second, maintain the running sum incrementally with recursion or Gray-code order, adding or removing one item per step, instead of rebuilding a list for each mask. That reduces the per-subset cost from O(n) toward O(1) and brings the total close to O(2^n).
Exercise
Your O(n^2) solution passes local tests with random inputs of size n = 3,000 in 0.4 seconds of Python. The limit is n ≤ 3,000, but there are up to 50 test cases and no bound on their total size. Is it safe? What should you check?
Show answer
It is not safe. The worst case is 50 × 3,000^2 / 2 ≈ 2.25×10^8 pair checks, roughly 20 seconds or more in Python. Also, random inputs may have triggered early returns, so 0.4 seconds might understate even a single worst-case run. Benchmark one input with no valid answer, multiply by 50, and either switch to a faster algorithm or confirm that the total input size is bounded.