Big O Notation

intermediate15 min

Understanding Big O Notation

Big O describes how runtime or memory grows as input size increases. It lets you compare two approaches before you commit to one. For picking an approach from contest constraints, see Reading Constraints to Choose an Approach.

Key Rules for Big O Analysis

  • Drop Constants: O(2n) = O(n)
  • Drop Lower Order Terms: O(n² + n) = O(n²)
  • Worst Case: We analyze the worst-case scenario
  • Input Size: n represents the size of the input

Common Big O Complexities

Nested Loops Analysis

  • Two nested loops: O(n²)
  • Three nested loops: O(n³)
  • Loop with different bounds: O(n × m)
  • Loop with halving: O(log n)

Space Complexity Examples

  • O(1): Using only a few variables
  • O(n): Creating an array of size n
  • O(n²): Creating a 2D array of size n×n
  • O(log n): Recursive calls with halving