
Python DSA Notes
What Does Big O Mean? Think About Growth Before Memorizing a Table
Understand O(1), O(N), and O(N²) by counting how work grows, then compare that growth with the input constraints.
Python DSA 笔记
Big O 到底在说什么?先看增长速度,不要先背复杂度表
通过计算工作量如何增长,理解 O(1)、O(N) 和 O(N²),再结合输入上限判断算法是否可行。
Beginners often treat O(1), O(N), and O(N²) as formulas to memorize. Big O answers a more useful question: as the input size grows, how does the amount of work grow? It describes a growth pattern, not an exact stopwatch time.
Three Growth Patterns
| Input size N | O(1) | O(N) | O(N²) |
|---|---|---|---|
| 10 | 1 | 10 | 100 |
| 100 | 1 | 100 | 10,000 |
| 1,000 | 1 | 1,000 | 1,000,000 |
Constant work stays roughly unchanged. Linear work grows in proportion to N. Quadratic work grows as N × N, so increasing N by 100 can increase the work by 10,000.
O(1): Fixed Work
distance = abs(a - c) + abs(b - d)
This expression performs a fixed number of arithmetic operations regardless of the coordinate values. The CCC 2017 J3 Exactly Electrical decision is O(1). Constant time does not mean one line; it means the operation count does not grow with N.
O(N): One Pass
total = 0
for value in values:
total += value
A list of N items causes N loop iterations. Two consecutive scans cost N + N = 2N, which is still O(N) because Big O ignores fixed multipliers and keeps the growth shape.
O(N²): Work for Every Pair
for i in range(n):
for j in range(n):
compare(values[i], values[j])
The outer loop runs N times and starts an N-step inner loop each time, for about N² operations. Comparing only distinct pairs gives N(N-1)/2; its leading growth is still quadratic.
Do not classify code by indentation alone. Consecutive loops add, nested ranges often multiply, and library calls such as sorting contain their own algorithms.
Constraints Turn Big O into a Decision
An O(N³) solution may be completely reasonable at N≤100, as in USACO Daisy Chains. At N=100,000, an O(N²) solution implies roughly ten billion pair checks and is usually unacceptable. Language, constants, operation cost, and time limits still matter, so the usual limits table is a screening heuristic rather than a guarantee.
Use this workflow:
- Define what
Nmeasures. - Identify which work grows with
N. - Add consecutive work and multiply genuinely nested work.
- Keep the dominant growth term.
- Estimate the count at the maximum allowed
N.
Common Misunderstandings
- Big O is an exact running time. It is not; it describes growth.
- Any two loops imply
O(N²). Consecutive loops remain linear. - Multiplying a number by
NcostsO(N). One arithmetic multiplication is fixed work in this model. - A lower Big O automatically makes code better. Correctness, clarity, and actual constraints still matter.
O(N²)is always too slow. It can be ideal whenNis small.
Practice
- What is the Big O of
3N+5operations? - An outer loop runs
Ntimes and its inner body always runs 10 times. What is the complexity? - Compute
N³atN=100. Why can some problems accept it? - What is the complexity of sorting and then scanning once?
- Take an old solution and define its
Nand worst-case order of growth.
One Sentence to Remember
Big O describes how work grows with input size: count the work, read the constraints, and then decide whether the algorithm is fast enough.
很多初学者第一次看到 O(1)、O(N)、O(N²),会把它们当成另一套公式背下来。其实 Big O 想回答的是一个很朴素的问题:当输入规模变大时,程序需要做的工作会怎样增长?
Big O 不是秒表
Big O 通常不告诉你程序一定运行多少毫秒,也不直接比较两台电脑谁更快。它把注意力放在输入规模 N 与操作次数之间的关系。
假设处理 10 个数据时,程序执行 10 次;处理 100 个数据时执行 100 次;处理 1000 个数据时执行 1000 次。操作次数跟着 N 同比例增长,我们把这种增长写成 O(N)。
先比较三种增长
| 输入规模 N | O(1) | O(N) | O(N²) |
|---|---|---|---|
| 10 | 1 | 10 | 100 |
| 100 | 1 | 100 | 10,000 |
| 1,000 | 1 | 1,000 | 1,000,000 |
当 N 只从 10 增加到 1000:
O(1)的工作量基本不变;O(N)增加 100 倍;O(N²)增加 10,000 倍。
这就是为什么我们关注增长速度。小输入时几种写法可能都很快,输入放大后差距才真正出现。
O(1):固定次数的工作
distance = abs(a - c) + abs(b - d)
不管坐标是 2 还是 2,000,000,这行仍然只做固定次数的减法、绝对值和加法。CCC 2017 J3 Exactly Electrical 的完整判定只需要固定数量的算术和条件操作,因此是 O(1)。
O(1) 不等于“只运行一行”,而是操作次数不会随着 N 增长。
O(N):看一遍所有输入
total = 0
for value in values:
total += value
如果列表有 N 个元素,循环执行 N 次。输入扩大 10 倍,主要工作量也大约扩大 10 倍,因此是 O(N)。
两个先后执行的 N 次循环仍然是 O(N):
N + N = 2N -> O(N)
Big O 忽略固定倍数,因为 2N 和 N 的增长形状相同。
O(N²):为每个元素再看一遍所有元素
for i in range(n):
for j in range(n):
compare(values[i], values[j])
外层循环 N 次,每一次内层又循环 N 次,总工作量约为 N × N = N²。
如果只比较不同的无序对:
for i in range(n):
for j in range(i + 1, n):
compare(values[i], values[j])
精确次数是 N(N-1)/2,但增长仍然由 N² 主导,所以仍写成 O(N²)。Big O 不是在抹掉数学,而是在保留决定规模的部分。
不要看到嵌套就机械写 O(N²)
循环层数只是线索,不是答案。真正要问的是:每一层循环实际执行多少次?
for i in range(n):
print(i)
for j in range(n):
print(j)
这是两个并列循环,总次数 2N,所以是 O(N),不是 O(N²)。
而下面这段即使没有嵌套循环,也可能执行 N log N 级别的工作,因为排序函数内部已经完成了算法:
values.sort()
分析复杂度要理解操作,不只是数缩进。
为什么还要看约束
Big O 只有和输入上限放在一起才有决策价值。
| 输入上限 | 常见可行目标(经验筛选) |
|---|---|
N ≤ 100 |
O(N²),有时 O(N³) 也可行 |
N ≤ 2,000 |
谨慎使用 O(N²) |
N ≤ 100,000 |
通常寻找 O(N log N) 或 O(N) |
N ≤ 1,000,000 |
通常需要接近 O(N) |
这不是绝对的时间保证。语言、常数、操作类型和时限都会影响实际运行时间,但它能帮你快速排除明显不可行的方案。
例如 USACO Daisy Chains 的解法最坏是 O(N³),听起来很慢;但题目给 N≤100,总工作量仍然可控。相反,如果 N=100,000,O(N²) 约等于一百亿次比较,通常不能接受。
一套实用分析方法
看到一段代码时,按这个顺序问:
N代表什么?列表长度、节点数,还是字符串长度?- 哪一部分工作会随
N增长? - 循环是并列还是嵌套?内层范围是否变化?
- 最主要的增长项是什么?
- 把它和题目的最大
N放在一起,工作量大约是多少?
常见误解
- “O(N) 一定比 O(N²) 快。” 对足够大的同类输入通常如此,但小输入、常数和操作类型仍会影响实际时间。
- “Big O 是准确运行时间。” 它描述增长上界,不是秒表结果。
- “两个循环就是 O(N²)。” 并列循环相加,嵌套循环才通常相乘。
- “乘以 N 就是 O(N)。” 一次算术乘法仍是固定工作;重复执行 N 次才随 N 增长。
- “复杂度越低,代码就一定越好。” 正确性、可读性和题目约束同样重要。
小练习
- 一个循环执行
3N+5次,Big O 是什么? - 一个外层循环执行
N次,内层固定执行 10 次,Big O 是什么? - 当
N=100时,N³是多少?为什么某些题仍能接受? - 分析“先排序,再扫描一次”的总复杂度。
- 找一段自己的旧代码,写出
N的含义和最坏情况下的操作数量级。
一句话记住
Big O 描述输入变大时工作量怎样增长;先数工作,再看约束,最后才决定算法够不够快。
Questions or feedback?
Have a question about this article or want to suggest an improvement? Send us a private message.
有问题或建议?
如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。