Simple Algorithm
Algorithms & Data Structures · Optimal · 24 min

Constraints & Complexity Budgets

Read n and the time limit, and know which complexities fit.

A problem's constraints are a message from its author. "n≤20n \le 20" says exponential time is welcome, "n≤106n \le 10^6" says O(nlog⁡n)O(n \log n) at most, and "at most 30 queries" says binary search. This lesson turns the message into arithmetic, then shows where arithmetic stops: when a conditional lower bound says that no much faster algorithm is likely to exist.

What you’ll learn

  • Turn time and memory limits into operation and memory budgets, and invert a budget to the largest feasible nn for nkn^k, nlog⁡nn \log n and 2n2^n.
  • Account for constant factors, caches, language speed, hidden parameters and output size when a budget is tight.
  • Prove the information-theoretic lower bound for yes/no queries, and use it to read the query limits of interactive problems.
  • State SETH and the 3SUM and APSP conjectures, prove that SETH implies the orthogonal vectors conjecture, and use such conditional bounds to decide when to stop optimizing.

Budgets, exactly

DerivationInverting a budget
  1. n2≤108  ⟺  n≤104,n3≤108  ⟺  n≤464n^2 \le 10^8 \iff n \le 10^4, \qquad n^3 \le 10^8 \iff n \le 464

    Polynomials. nk≤Bn^k \le B exactly when n≤B1/kn \le B^{1/k}. At B=108B = 10^8:

  2. 2n≤108  ⟺  n≤262^n \le 10^8 \iff n \le 26

    Exponentials. 2n≤B2^n \le B exactly when n≤log⁡2Bn \le \log_2 B, and log⁡2108≈26.6\log_2 10^8 \approx 26.6:

  3. n1=Blog⁡2B≈3.76×106,n2=Blog⁡2n1≈4.58×106,n3≈4.520×106n_1 = \frac{B}{\log_2 B} \approx 3.76 \times 10^6, \quad n_2 = \frac{B}{\log_2 n_1} \approx 4.58 \times 10^6, \quad n_3 \approx 4.520 \times 10^6

    nlog⁡nn \log n. The equation nlog⁡2n=Bn \log_2 n = B has no closed form, but the map n↦B/log⁡2nn \mapsto B / \log_2 n converges quickly from n0=Bn_0 = B to its fixed point:

  4. nmax⁡=4,523,071  ≈  Blog⁡2(B/log⁡2B)n_{\max} = 4{,}523{,}071 \;\approx\; \frac{B}{\log_2 (B / \log_2 B)}

    The largest integer with nlog⁡2n≤108n \log_2 n \le 10^8 is 4,523,0714{,}523{,}071, so the second iterate, B/log⁡2(B/log⁡2B)B / \log_2(B / \log_2 B), is already within about 1%. At this budget an nlog⁡nn \log n algorithm handles about 22 times fewer items than a linear one, because log⁡2n≈22\log_2 n \approx 22 there.

  5. nk:  nmax⁡↦c1/k nmax⁡,2n:  nmax⁡↦nmax⁡+log⁡2cn^k:\; n_{\max} \mapsto c^{1/k}\, n_{\max}, \qquad 2^n:\; n_{\max} \mapsto n_{\max} + \log_2 c

    A faster machine. Multiplying the speed by cc multiplies the feasible nn by c1/kc^{1/k} for nkn^k, but only adds log⁡2c\log_2 c for 2n2^n:

DataEntriesMemory
32-bit integers10710^740 MB
64-bit integers10710^780 MB
a 5000×50005000 \times 5000 table of 32-bit integers2.5×1072.5 \times 10^7100 MB
Held–Karp's table for 20 cities, 220×202^{20} \times 20 32-bit entries2.1×1072.1 \times 10^784 MB
a bitset over 10910^9 values10910^9 bits125 MB
a Python list of 10610^6 distinct integers10610^6about 36 MB (an 8-byte pointer plus a 28-byte object each), against 4 MB in C++
Memory arithmetic with 1 MB = 10610^6 bytes. The Python figure is CPython on a 64-bit machine.
Predict before you look

An edit-distance DP stores the full table dp[i][j]\mathrm{dp}[i][j] for two strings of length 10410^4 each, as 32-bit integers. About how many megabytes does the table need?

Show the answer

400 MB

(104+1)2≈108(10^4 + 1)^2 \approx 10^8 entries of 4 bytes: about 400 MB, over a 256 MiB limit even though 10810^8 steps fit in a second. Each row depends only on the previous one, so two rows of 104+110^4 + 1 entries, about 80 KB, compute the distance; recovering the alignment as well in linear space is Hirschberg's trick, in Reconstructing Solutions & Saving Space.

Constants, caches and hidden parameters

O(⋅)O(\cdot) hides constants, and when two candidate complexities are close at the actual nn, the constants decide. Compare nlog⁡2nn \log^2 n, say a segment tree with a binary search inside every query, with nnn\sqrt{n}, say a square-root decomposition. The two are exactly equal at n=216=65,536n = 2^{16} = 65{,}536, where log⁡22n=162=256=n\log_2^2 n = 16^2 = 256 = \sqrt{n}, and at n=105n = 10^5 they differ by 15%: 2.76×1072.76 \times 10^7 against 3.16×1073.16 \times 10^7. At that size, choose the one with the smaller constant or the simpler code.

Constants come from many places. A sequential scan of an array streams through the cache at memory bandwidth, while each cache miss on a pointer chase costs on the order of a hundred nanoseconds, the time of hundreds of arithmetic operations; this is why an array-based heap beats a pointer-based one, and why the Optimal lesson The Memory Hierarchy & Locality exists. Python adds a factor of 10 to 100 per simple operation, which is why the same solution can pass in C++ and fail in Python.

The statement says…What it changes
"the sum of nn over all test cases is at most 2×1052 \times 10^5"total work is O(∑nlog⁡n)O(\sum n \log n), but no test may cost time proportional to the largest possible nn
values are at most 10610^6arrays indexed by value: counting sort, a sieve, frequency tables
strings over 26 lowercase lettersa factor of 26 is affordable: one prefix-count table per letter
a second parameter k≤20k \le 202k2^k states are fine: bitmasks over kk, not over nn
all qq queries are known in advanceoffline tricks: sort the queries, sweep, or Mo's algorithm in O((n+q)n)O((n + q)\sqrt{n})
"print every pair"the output alone may be Θ(n2)\Theta(n^2): aim for O(n+output)O(n + \text{output})
"answer modulo 109+710^9 + 7"the answer is huge: counting, almost always DP or combinatorics
Hidden parameters: each one changes the budget or points to a technique.
Check your understanding

There are T≤104T \le 10^4 test cases, each with n≤2×105n \le 2 \times 10^5, and the sum of nn over all tests is at most 2×1052 \times 10^5. Your program clears an array of size 2×105+12 \times 10^5 + 1 at the start of every test, then runs an O(nlog⁡n)O(n \log n) algorithm. What happens?

  1. It is fine: each test costs O(nlog⁡n)O(n \log n)
  2. It is too slow: the clearing alone costs about 2×1092 \times 10^9 steps over 10410^4 tests
  3. It is fine: clearing memory is free
  4. It is too slow: O(nlog⁡n)O(n \log n) summed over the tests exceeds the budget
Show the answer

B. It is too slow: the clearing alone costs about 2×1092 \times 10^9 steps over 10410^4 tests

The useful work is at most ∑nlog⁡2n≤2×105×18≈3.6×106\sum n \log_2 n \le 2 \times 10^5 \times 18 \approx 3.6 \times 10^6 steps, but 10410^4 clearings of 2×1052 \times 10^5 entries are 2×1092 \times 10^9 steps, about 20 seconds at 10810^8 per second. Clear only the first nn entries, or tag entries with the test number instead of clearing.

Query limits and the information-theoretic bound

In an interactive problem the judge hides something and answers your questions, and the statement caps how many you may ask. The cap is a hint, because counting the possible answer patterns bounds every strategy at once.

DerivationProof
  1. questions(x)  =  depth of the leaf reached by x\text{questions}(x) \;=\; \text{depth of the leaf reached by } x

    Strategies are trees. The first question is the root, each answer leads to the next question, and each leaf announces a candidate. The number of questions asked about xx is the depth of the leaf that xx reaches.

  2. td  ≥  N⟹d  ≥  ⌈log⁡tN⌉t^d \;\ge\; N \quad\Longrightarrow\quad d \;\ge\; \lceil \log_t N \rceil

    One leaf per candidate. Two candidates reaching the same leaf get the same announcement, which is wrong for one of them, so there are at least NN leaves. A tree of depth dd with at most tt children per node has at most tdt^d leaves:

  3. 2−1N∑idi  ≤  1N∑i2−di  ≤  1N⟹1N∑idi  ≥  log⁡2N2^{-\frac{1}{N}\sum_i d_i} \;\le\; \frac{1}{N}\sum_i 2^{-d_i} \;\le\; \frac{1}{N} \quad\Longrightarrow\quad \frac{1}{N}\sum_i d_i \;\ge\; \log_2 N

    On average. In a binary tree, leaf depths d1,…,dNd_1, \dots, d_N satisfy Kraft's inequality, ∑i2−di≤1\sum_i 2^{-d_i} \le 1. The geometric mean is at most the arithmetic mean, so

  4. candidates left after d questions  ≥  ⌈N/2d⌉\text{candidates left after } d \text{ questions} \;\ge\; \left\lceil N / 2^d \right\rceil

    As an adversary. The same bound, told as a game: the judge answers each question so that the larger group of candidates stays consistent, and after dd yes/no questions at least N/2dN / 2^d candidates remain. Binary search, which halves the candidates every time, meets the bound exactly.

A limit like…Suggests
⌈log⁡2N⌉\lceil \log_2 N \rceil yes/no queries: 20 for N=106N = 10^6, 30 for N=109N = 10^9binary search; every query must halve the candidates
n+⌈log⁡2n⌉−2n + \lceil \log_2 n \rceil - 2 comparisons to find the second largesta knockout tournament, then the maximum among the players the winner beat
⌈3n/2⌉−2\lceil 3n/2 \rceil - 2 comparisons to find both the minimum and the maximumcompare in pairs: the larger of each pair competes for the maximum, the smaller for the minimum
3 weighings to find the odd coin among 12, heavier or lighter3 outcomes per weighing: 33=27≥243^3 = 27 \ge 24 cases, so a strategy is not ruled out (and one exists)
⌈log⁡2n!⌉\lceil \log_2 n! \rceil comparisons to sort nn itemsthe counting bound itself; the lesson The Ω(n log n) Sorting Lower Bound develops it
Every row is a counting or adversary bound; the second and third are proved in Lower Bounds by Adversary Arguments.

When to stop: conditional lower bounds

Your best algorithm is O(n2)O(n^2) and n=105n = 10^5: should you keep looking for something faster? For most problems in P nobody can prove a superlinear lower bound in a general model of computation. Fine-grained complexity answers conditionally instead: it reduces a few core problems to many others, so that a faster algorithm for any of them would break a conjecture that has resisted decades of attack.

DerivationProof: split the variables, list both halves
  1. N  =  2n/2 assignments a of the first half,N assignments b of the secondN \;=\; 2^{n/2} \text{ assignments } a \text{ of the first half}, \quad N \text{ assignments } b \text{ of the second}

    Split the nn variables into two halves of n/2n/2 and list all assignments of each half:

  2. ua[j]=[ a satisfies no literal of Cj ],vb[j]=[ b satisfies no literal of Cj ]u_a[j] = \big[\, a \text{ satisfies no literal of } C_j \,\big], \qquad v_b[j] = \big[\, b \text{ satisfies no literal of } C_j \,\big]

    Give each half-assignment a vector with one coordinate per clause CjC_j, set to 1 exactly when that half-assignment fails to satisfy CjC_j on its own:

  3. (a,b)⊨φ  ⟺  ∑j=1mua[j] vb[j]=0(a, b) \models \varphi \iff \sum_{j=1}^{m} u_a[j]\, v_b[j] = 0

    The full assignment (a,b)(a, b) satisfies CjC_j exactly when one of the halves does, that is when ua[j] vb[j]=0u_a[j]\,v_b[j] = 0. So the formula is satisfiable exactly when some pair of vectors is orthogonal:

  4. (2n/2)2−ε poly(m)  =  2(1−ε/2) n poly(m)\big(2^{n/2}\big)^{2-\varepsilon}\,\mathrm{poly}(m) \;=\; 2^{(1-\varepsilon/2)\,n}\,\mathrm{poly}(m)

    Building the 2N2N vectors costs 2n/2 poly(m)2^{n/2}\,\mathrm{poly}(m), and the assumed OV algorithm, with d=md = m, finishes in the time below. For kk-SAT, the sparsification lemma (Impagliazzo, Paturi & Zane, 2001) splits a kk-CNF, for any δ>0\delta > 0, into at most 2δn2^{\delta n} kk-CNFs with O(n)O(n) clauses each. With δ=ε/4\delta = \varepsilon/4 the total is 2(1−ε/4)n poly(n)2^{(1-\varepsilon/4)n}\,\mathrm{poly}(n), below 2(1−ε/5)n2^{(1-\varepsilon/5)n} for large nn, for every kk: SETH fails.

OV in turn reduces to sequence problems: NN vectors can be encoded in strings of length N poly(d)N\,\mathrm{poly}(d) so that a strongly subquadratic algorithm for edit distance (Backurs & Indyk, 2015), longest common subsequence (Abboud, Backurs & Vassilevska Williams; Bringmann & Künnemann, both 2015) or dynamic time warping would solve it. Likewise 3SUM reduces to many problems in computational geometry (Gajentaan & Overmars, 1995), and APSP is subcubically equivalent to finding a negative-weight triangle (Vassilevska Williams & Williams, 2010).

Read the constraints with this in mind. If n=105n = 10^5 and the problem is general edit distance, an O(n1.9)O(n^{1.9}) algorithm would be a research breakthrough, so look for an escape the instance offers: a small answer (distance at most kk: compute a band of width 2k+12k + 1, O(nk)O(nk)), small values (3SUM with values in [−U,U][-U, U]: polynomial multiplication by the FFT, O(n+Ulog⁡U)O(n + U \log U)), special structure, or an approximation.

Key takeaways

  • An operation budget is speed times time, about 10810^8 per second. Invert it: B\sqrt{B} for n2n^2, B3\sqrt[3]{B} for n3n^3, log⁡2B\log_2 B for 2n2^n, and about B/log⁡2(B/log⁡2B)B / \log_2(B / \log_2 B) for nlog⁡nn \log n, which is 4.5 million at B=108B = 10^8. Count bytes too: 10710^7 32-bit integers take 40 MB.
  • A machine cc times faster multiplies the feasible nn by c1/kc^{1/k} for nkn^k but adds only log⁡2c\log_2 c for 2n2^n: algorithms, not machines, move exponential walls.
  • Constants decide between close complexities (nlog⁡2nn \log^2 n and nnn\sqrt{n} are equal at n=65,536n = 65{,}536), and hidden parameters (sums over tests, value ranges, alphabets, second parameters, offline queries, output size) change the budget.
  • With yes/no answers, dd questions distinguish at most 2d2^d candidates, so a limit near ⌈log⁡2N⌉\lceil \log_2 N \rceil queries means binary search.
  • Fine-grained conditional lower bounds (SETH, 3SUM, APSP) tell you when to stop looking for a better exponent and start looking for structure in the instance.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Ignoring constant factors, what is the largest nn with nlog⁡2n≤108n \log_2 n \le 10^8?

  1. 10810^8
  2. about 4.5×1064.5 \times 10^6
  3. 10610^6
  4. about 10410^4
Show the answer

B. about 4.5×1064.5 \times 10^6

Iterating n↦108/log⁡2nn \mapsto 10^8 / \log_2 n from 10810^8 gives 3.76×1063.76 \times 10^6, 4.58×1064.58 \times 10^6, 4.52×1064.52 \times 10^6: the exact answer is 4,523,0714{,}523{,}071.

Question 2

Your O(2n)O(2^n) solution handles n=30n = 30 within the limit. On a machine 1,000 times faster, about how large an nn can it handle?

  1. 30,000
  2. about 40
  3. about 950
  4. 60
Show the answer

B. about 40

2n≤1000⋅2302^{n} \le 1000 \cdot 2^{30} gives n≤30+log⁡21000≈40n \le 30 + \log_2 1000 \approx 40. A thousandfold speedup buys ten more items; a better algorithm, such as meet in the middle, would double nn.

Question 3

A judge hides one of 1,000 possible values and answers any yes/no question you ask. What is the fewest number of questions that always suffices?

  1. 9
  2. 10
  3. 32
  4. 500
Show the answer

B. 10

dd questions have at most 2d2^d answer patterns, so 2d≥10002^d \ge 1000 forces d≥10d \ge 10, and halving the candidates each time achieves ⌈log⁡21000⌉=10\lceil \log_2 1000 \rceil = 10.

Question 4

Your edit-distance DP takes O(n2)O(n^2) time and n=105n = 10^5. What does the Backurs–Indyk theorem tell you?

  1. Edit distance is NP-hard, so no polynomial-time algorithm exists
  2. An O(n2−ε)O(n^{2-\varepsilon}) algorithm for all inputs would refute SETH, so look for structure in the constraints instead
  3. An O(nlog⁡n)O(n \log n) algorithm exists by the FFT
  4. No algorithm can beat n2n^2 steps, unconditionally
Show the answer

B. An O(n2−ε)O(n^{2-\varepsilon}) algorithm for all inputs would refute SETH, so look for structure in the constraints instead

The bound is conditional: strongly subquadratic edit distance would solve CNF-SAT with nn variables and mm clauses in 2(1−δ)n poly(m)2^{(1-\delta)n}\,\mathrm{poly}(m) time for some δ>0\delta > 0. So look for what this instance allows, such as a small bound kk on the distance (a band of width 2k+12k + 1 gives O(nk)O(nk)), or settle for an approximation.

Further reading

  • A. Laaksonen, Guide to Competitive Programming, 2nd ed. (Springer, 2020).
  • R. Impagliazzo & R. Paturi, "On the complexity of k-SAT," Journal of Computer and System Sciences 62(2) (2001).
  • R. Williams, "A new algorithm for optimal 2-constraint satisfaction and its implications," Theoretical Computer Science 348 (2005).
  • A. Backurs & P. Indyk, "Edit Distance Cannot Be Computed in Strongly Subquadratic Time (unless SETH is false)," Proceedings of STOC (2015).
  • V. Vassilevska Williams, "On some fine-grained questions in algorithms and complexity," Proceedings of the International Congress of Mathematicians (ICM 2018).