Sub topic 2
Will It Run in Time? Estimating Brute-Force Cost
This chapter assumes you can read Python loops and recursion and know introductory Big-O notation. Before you write a brute-force solution, count how many candidates it checks and how much work each check costs. Then compare that number to the input limits.
The Budget Rule of Thumb
A typical judge or test harness allows about 1 second. Plain Python handles roughly 10^7 simple operations per second. Compiled languages handle about 10^8. To estimate the cost, multiply the number of candidates by the cost of each check, then compare the result to your budget.
| Search space | Cost | Largest n for about 10^7 operations |
|---|---|---|
| All pairs | O(n^2) | about 3,000 |
| All triples | O(n^3) | about 200 |
| All subsets | O(2^n · n) | about 20 |
| All orderings | O(n! · n) | about 9 |
Trying Every Subset with Bitmasks
A set of n items has 2^n subsets. Each integer from 0 to 2^n − 1 can stand for one subset: bit i of the integer says whether item i is included.
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 function sums up to n items for each of the 2^n masks, so the total cost is O(2^n · n). At n = 20 that comes to about 2 × 10^7 operations.
Trying Every Ordering with Permutations
Some problems ask for the best order. The traveling-salesman problem is one example. If you fix the starting city, (n−1)! orderings remain to check.
import itertools
import math
def shortest_tour(dist):
n = len(dist)
best = math.inf
for perm in itertools.permutations(range(1, n)):
route = (0,) + perm + (0,)
cost = sum(dist[a][b] for a, b in zip(route, route[1:]))
best = min(best, cost)
return best
dist = [[0, 2, 9, 10], [1, 0, 6, 4], [15, 7, 0, 8], [6, 3, 12, 0]]
print(shortest_tour(dist)) # 21Factorials grow much faster than powers of two. At n = 11 the function checks 10! ≈ 3.6 million orderings, and each costs O(n). In Python that is already several seconds.
When Brute Force Is Good Enough to Ship
Ship the brute-force version when the input size is known to stay small, when the estimate fits the budget with room to spare, or when the code runs rarely, such as a one-off script or a nightly batch job. Code that is simple and obviously correct is cheaper to review and maintain than a clever algorithm nobody needed.
Exercise
A problem gives n ≤ 18 items and asks whether any subset has a product equal to a target. You check each subset by multiplying its items. Is bitmask brute force fast enough in Python?
Show answer
Yes. The cost is 2^18 · 18 ≈ 4.7 × 10^6 operations, which is under the budget of about 10^7 per second.
Exercise
Why does shortest_tour fix city 0 as the start instead of trying all n! orderings?
Show answer
A tour is a cycle, so rotating it gives a tour with the same cost. Fixing the start removes those duplicate rotations and cuts the work by a factor of n.