Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 15 min · revision 1

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

  1. The problem
  2. Step 1: plug input limits into candidate bounds
  3. Step 2: extrapolate measurements and check model limits
  4. Check your understanding
  5. Apply it
  6. Review prompt

Lessons of Complexity Analysis

  1. Counting Steps Instead of Seconds Concept · 20 min
  2. Reading Loops: From Code to a Bound Worked example · 25 min
  3. Worst Case, Average Case and Amortized Cost Concept · 20 min
  4. Budgeting Operations from Input Limits Worked example · 15 min
  5. Lab: Timing Growth Curves with timeit Lab · 30 min
  6. 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:

Python · step counts at three input limits, and grid memory
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")
Expected output (64-bit CPython 3.12)
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 cell

Read those numbers against a 10^7 steps-per-second Python budget:

  • n <= 16: 2^16 = 65,536 subsets. Even if each subset costs 16 simple steps, that is about 10^6 steps, a fraction of a second, so a cap this small signals that trying every subset is affordable, and a recursive search only 16 levels deep stays far below Python's default sys.getrecursionlimit() of 1,000. Check the work per subset, though: a bitmask dynamic program that spends n^2 = 256 steps on each of the 65,536 states needs about 1.7 * 10^7 steps, close to two seconds in pure Python. At n = 30, 2^30 is over a billion subsets, minutes of work even at one step each.
  • n = 1,000: n^2 = 10^6, comfortably within 10^7, so an O(n^2) solution usually passes.
  • n = 100,000 (10^5): O(n log n) is ~1.7 * 10^6 steps (viable), whereas O(n^2) is 10^10 steps, a thousand times over budget. A limit of 10^5 rules out quadratic algorithms and tells you to target O(n log n) or O(n).
  • n >= 10^8: even O(n) exceeds 10^7 simple Python loop iterations, pointing toward O(log n) or O(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

Practice check · 3 questions

Budgeting from constraints

Decide viability and scaled runtimes from problem limits.

Q1. A matching service compares every pair among `n = 20,000` records. Someone proposes precomputing all answers in an `n x n` list-of-lists of `True`/`False` flags on a worker with `2 GB` of RAM. What does the memory budget say?
Q2. A job must sort `n = 10^6` integers within about one second. Two `O(n log n)` options exist: the built-in `sorted()`, or a hand-written recursive merge sort in pure Python. Which judgement is sound?
Q3. A job has a `10 s` window and must process `500` independent batches of up to `n = 2,000` records each, in one Python process at about `10^7` simple steps per second. Is an `O(n^2)` pairwise check inside each batch within budget?
Practice only: not graded, not saved, not evidence.

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:

  1. n <= 18 items, choose a valid subset maximising a total score.
  2. n <= 3,000 items, find the closest pair of 2D coordinates.
  3. n <= 200,000 records, group or sort logs by timestamp.
  4. 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:

  1. What complexity classes are ruled out when a Python problem sets n <= 10^5 and a ~1 s budget, and why?
  2. If an O(n log n) function takes 0.1 s at n = 10,000, how do you estimate its runtime at n = 1,000,000?
  3. Name two situations where a function stays under the 10^7 step budget yet still fails or times out.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check