Courses / Physics I
Computer Science

Complexity and efficiency basics

Physics I 161 words Free to read

Big-O Notation

Big-O notation describes how an algorithm's run time scales with input size nn.

Big-ONameExample
O(1)O(1)ConstantArray index access
O(logn)O(\log n)LogarithmicBinary search
O(n)O(n)LinearSingle loop
O(nlogn)O(n\log n)LinearithmicMerge sort
O(n2)O(n^2)QuadraticNested loops
O(2n)O(2^n)ExponentialBrute-force subsets

Space complexity measures memory usage by this exact same logic.

Scaling and Pitfalls

To determine complexity: single loop is O(n)O(n), nested loop is O(n2)O(n^2), and halving the input is O(logn)O(\log n).

Practical example: Computing pairwise distances between nn particles uses nested loops, yielding O(n2)O(n^2). Advanced methods like Barnes-Hut reduce this to O(nlogn)O(n\log n) using spatial trees.

Common pitfall: Big-O hides constants. An O(n2)O(n^2) method can beat an O(nlogn)O(n\log n) one on small inputs. Complexity classes predict scaling, not micro-benchmarks.

Two growth curves cross: the asymptotically worse one wins for a while

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

13practice questions
2interactive scenes

Computer Science