Courses / Physics I
Computer Science

Complexity and efficiency basics

Physics I 224 words Free to read

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

Common complexity classes

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

How to determine complexity

Space complexity measures memory usage by the same logic.

Practical example — Computing all pairwise distances between nn particles:

# O(n^{2}) — unavoidable for all-pairs
for i in range(n):
    for j in range(i + 1, n):
        dist = np.linalg.norm(pos[i] - pos[j])

For large nn, algorithms like Barnes-Hut (O(nlogn)O(n\log n)) use spatial trees to approximate distant interactions.

Physics link: Molecular dynamics with NN particles requires O(N2)O(N^{2}) force evaluations per time step. Reducing this to O(NlogN)O(N\log N) via fast multipole methods enabled simulations of millions of atoms.
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 which code wins today’s benchmark.

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
Start Physics I free

Computer Science