Budgeting Operations from Input Limits
Translate input-size constraints (n <= 16 through n = 10^5+) into viable complexity targets, extrapolate small-n timings to large limits, and spot when Python constants change the budget.
Contentsand lesson path
On this page
- The problem
- Step 1: plug input limits into candidate bounds
- Step 2: extrapolate measurements and check model limits
- Check your understanding
- Apply it
- Review prompt
Lessons of Complexity Analysis
- Counting Steps Instead of Seconds Concept · 20 min
- Reading Loops: From Code to a Bound Worked example · 25 min
- Worst Case, Average Case and Amortized Cost Concept · 20 min
- Budgeting Operations from Input Limits Worked example · 15 min
- Lab: Timing Growth Curves with timeit Lab · 30 min
- Check: Predict, Then Measure Knowledge check · 8 questions
What you will learn
- Use input-size limits to decide which complexity class a solution must reach (for example, n = 10^5 rules out O(n^2)).
Prerequisites: Python Foundations
01. The problem
Suppose a service specification or coding problem states that your input list can contain up to n = 100,000 (10^5) items and must finish within roughly one second. You already have a clean, readable O(n^2) prototype. Should you optimise it before testing at full scale, or might it squeak through?
You can answer that question in ten seconds before writing another line of code. Under a standard scenario assumption for CPython—roughly 10^7 simple Python loop iterations per second on a single core (we treat this as an illustrative rule of thumb, not a hardware constant)—you can plug n directly into each candidate complexity class and check whether the step count stays near 10^7.
02. Step 1: plug input limits into candidate bounds
Start by computing representative step counts for n = 16, n = 1,000, and n = 100,000 across common complexity classes, plus the memory of a 1,000 x 1,000 grid, which you will need in Step 2. Notice how each limit points toward a different family of algorithms:
import math
import sys
def estimated_steps(n: int) -> dict[str, int]:
return {
"O(log n)": max(1, round(math.log2(n))),
"O(n)": n,
"O(n log n)": n * max(1, round(math.log2(n))),
"O(n^2)": n * n,
}
for n in (16, 1_000, 100_000):
print(f"n={n:<7}", estimated_steps(n))
print("2^16 =", 2**16, "| 2^30 =", 2**30)
print("default recursion limit:", sys.getrecursionlimit())
grid = [[False] * 1_000 for _ in range(1_000)]
size = sys.getsizeof(grid) + sum(sys.getsizeof(row) for row in grid)
print(f"1,000 x 1,000 grid of False: {size:,} bytes, {size / 10**6:.2f} per cell")n=16 {'O(log n)': 4, 'O(n)': 16, 'O(n log n)': 64, 'O(n^2)': 256}
n=1000 {'O(log n)': 10, 'O(n)': 1000, 'O(n log n)': 10000, 'O(n^2)': 1000000}
n=100000 {'O(log n)': 17, 'O(n)': 100000, 'O(n log n)': 1700000, 'O(n^2)': 10000000000}
2^16 = 65536 | 2^30 = 1073741824
default recursion limit: 1000
1,000 x 1,000 grid of False: 8,064,856 bytes, 8.06 per cellRead those numbers against a 10^7 steps-per-second Python budget:
n <= 16:2^16 = 65,536subsets. Even if each subset costs16simple steps, that is about10^6steps, a fraction of a second, so a cap this small signals that trying every subset is affordable, and a recursive search only16levels deep stays far below Python's defaultsys.getrecursionlimit()of1,000. Check the work per subset, though: a bitmask dynamic program that spendsn^2 = 256steps on each of the65,536states needs about1.7 * 10^7steps, close to two seconds in pure Python. Atn = 30,2^30is over a billion subsets, minutes of work even at one step each.n = 1,000:n^2 = 10^6, comfortably within10^7, so anO(n^2)solution usually passes.n = 100,000(10^5):O(n log n)is~1.7 * 10^6steps (viable), whereasO(n^2)is10^10steps, a thousand times over budget. A limit of10^5rules out quadratic algorithms and tells you to targetO(n log n)orO(n).n >= 10^8: evenO(n)exceeds10^7simple Python loop iterations, pointing towardO(log n)orO(1)math.
Notice how quickly the feasible frontier shifts: between n = 1,000 and n = 100,000, n grows by 100x, yet O(n^2) step counts jump by 10,000x (10^6 to 10^10) while O(n log n) rises by only 170x (10^4 to 1.7 * 10^6). That contrast explains why a single pass of sorted() (O(n log n)) rescues problems whose brute-force pair loop (O(n^2)) times out.
03. Step 2: extrapolate measurements and check model limits
Input limits also let you scale a small local timing before waiting for a large run to hang. Suppose your O(n^2) prototype takes 0.3 s at n = 5,000, and production sends n = 150,000 (30 times larger). Because runtime scales with n^2, multiplying n by 30 multiplies the work by 30^2 = 900, turning 0.3 s into roughly 270 s (four and a half minutes). What if your algorithm were O(n) instead? Multiplying n by 30 would turn 0.3 s into about 9 s. And if it were O(n log n), log2(150,000) / log2(5,000) is roughly 17.2 / 12.3 ~ 1.4, so runtime scales by about 30 * 1.4 = 42x (~13 s).
The budget also covers the whole job, not one input. Suppose a nightly job must finish in 60 s and handles 300 independent files of up to n = 5,000 records each. An O(n^2) pass costs 2.5 * 10^7 steps per file (about 2.5 s), which looks fine for one file, but the job runs it 300 times: 7.5 * 10^9 steps, more than ten minutes. Multiply the per-input cost by the number of inputs (or sum over them) before you compare against the budget; files processed one after another in a single Python process do not overlap.
Simplification boundary (10^7 steps/sec): never treat 10^7 steps/sec as a physical law. Inside CPython, pure-Python bytecode loops run slower when every step allocates objects, parses strings, creates dicts, or invokes deep call stacks (so even 10^6 heavy iterations can exceed a second). Conversely, built-ins written in C—such as sum(), max(), sorted(), or bytes.find()—process far more elements per second than an explicit Python for loop. On our lab machine (CPython 3.12.13, Intel i7-3770, best of three runs), sorted() on 10^6 random integers took about 0.32 s, while the pure-Python recursive merge_sort_copy from the next lesson's lab took about 3.8 s on the same list: the same O(n log n) class, yet only one of them fits a one-second budget.
When input-limit budgeting is not enough: check memory and recursion depth alongside step counts. A full n x n list-of-lists holds n^2 cells, and each cell is an 8-byte pointer on a 64-bit build even when every cell refers to the same shared object such as False; the step-1 output measured about 8 MB for a 1,000 x 1,000 grid. At n = 10,000 that becomes 10^8 cells, about 800 MB of pointers before any loop runs. (sys.getsizeof(grid) alone reports only the outer list, which is why step 1 adds up the rows.) Likewise, a linear recursion of depth 10^5 hits Python RecursionError at about 1,000 frames long before CPU time runs out, a limit you will revisit in Recursion & Divide and Conquer. Check three budgets together before coding: CPU steps against ~10^7/s, peak memory against available RAM, and maximum call-stack depth against sys.getrecursionlimit().
04. Check your understanding
05. Apply it
Look at these four input limits and write down your target complexity class, estimated step count at 10^7 Python steps/sec, and why before writing any code:
n <= 18items, choose a valid subset maximising a total score.n <= 3,000items, find the closest pair of 2D coordinates.n <= 200,000records, group or sort logs by timestamp.n <= 10^9, compute the integer square root.
Next, test your predictions against real measurements on a live Python interpreter and learn how to guard benchmarks against runaway inputs in Lab: Timing Growth Curves with timeit.
06. Review prompt
Without looking back:
- What complexity classes are ruled out when a Python problem sets
n <= 10^5and a ~1 s budget, and why? - If an
O(n log n)function takes0.1 satn = 10,000, how do you estimate its runtime atn = 1,000,000? - Name two situations where a function stays under the
10^7step budget yet still fails or times out.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.