Courses / Computer Science I
Programming II

Complexity and Performance Trade-offs

Computer Science I 230 words Free to read

How an Algorithm Scales

Two programs can both be correct yet differ wildly in speed as data grows. Complexity analysis measures how an algorithm's cost grows with input size nn, ignoring hardware constants to focus on the growth shape.

Big-O notation expresses an upper bound on that growth. For large nn, growth classes dominate all constants; an O(nlogn)O(n \log n) sort beats O(n2)O(n^2) regardless of tuning.

Big-ONameExample
O(1)O(1)ConstantArray index access
O(logn)O(\log n)LogarithmicBinary search (halving step)
O(n)O(n)LinearScanning a list once
O(nlogn)O(n \log n)LinearithmicEfficient sorting
O(n2)O(n^2)QuadraticNested loops over data
O(2n)O(2^n)ExponentialTrying all subsets

Trade-offs and Pitfalls

Performance involves choices beyond raw loops. The space-time trade-off lets you spend more memory to save time, such as using a lookup table.

An algorithm also has best, average, and worst cases. Big-O usually describes the worst case unless specified otherwise.

O(1)<O(logn)<O(n)<O(nlogn)<O(n2)<O(2n)O(1) < O(\log n) < O(n) < O(n \log n) < O(n^2) < O(2^n)

Common pitfall: Judging performance on small inputs where constant factors dominate. An O(n2)O(n^2) algorithm can beat an O(nlogn)O(n \log n) one on tiny inputs, yet lose catastrophically as nn scales.
Complexity and Performance Trade-offs

Practise this lesson

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

11practice questions
2interactive scenes

Programming II