Spiral 50

0 of 19 lessons completed0 of 50 problems solved

Helper data structures and core patterns
Hash table
Stack
Queue
Heap
Core patterns
Problems
Linked lists, trees and graphs
Linked list
Tree
Binary Search Tree
Trie
Graph
Graph algorithms
Problems
Backtracking, greedy and dynamic programming
Backtracking
Greedy vs dynamic programming
Problems
Fundamentals

Big-O notation

Time and space complexity analysis with Big O notation is something that is asked for or expected from a candidate in every problem.

So you have to make sure that you can state them for your solutions.

The definition

If f(n)f(n) is the number of steps an algorithm takes on an input of size nn, f(n)=O(g(n))f(n) = O(g(n)) means there are a constant c>0c > 0 and a starting point n0n_0 such that

f(n)≤c⋅g(n)for every n≥n0f(n) \le c \cdot g(n) \quad \text{for every } n \ge n_0

In other words, from the starting point n0n_0, f(n)f(n) never rises above c⋅g(n)c \cdot g(n).

f(n)
c·g(n)
0501001502002503000102030405060708090100n₀nsteps

Example

The definition might be easier to understand with an example. Consider this code:

Sum, min and max
Python
def sum_min_max(nums: list[int]) -> tuple[int, int, int]:
total, smallest, largest = 0, nums[0], nums[0]
for num in nums:
total += num
smallest = min(smallest, num)
largest = max(largest, num)
return total, smallest, largest
function sumMinMax(nums) {
let total = 0, smallest = nums[0], largest = nums[0]
for (const num of nums) {
total += num
smallest = Math.min(smallest, num)
largest = Math.max(largest, num)
}
return [total, smallest, largest]
}
static int[] sumMinMax(int[] nums) {
int total = 0, smallest = nums[0], largest = nums[0];
for (int num : nums) {
total += num;
smallest = Math.min(smallest, num);
largest = Math.max(largest, num);
}
return new int[] { total, smallest, largest };
}

The first line and the return run once each, and the three lines inside the loop run nn times each. So the total number of operations is f(n)=3n+2f(n) = 3n + 2. In Big O notation, we can say that the time complexity is O(n)O(n).

This is because with c=4c = 4 and n0=2n_0 = 2, the line c⋅n=4nc \cdot n = 4n is never below f(n)=3n+2f(n) = 3n + 2 for any n≥n0n \ge n_0. So we found at least one pair of cc and n0n_0 for which c⋅nc \cdot n stays above 3n+23n + 2.

f(n) = 3n + 2
c·n = 4n
0510152025303540012345678910n₀ = 2noperations

In general, you can always drop constant factors and smaller terms. 2n+12n + 1 operations is written as O(n)O(n), and n2+n+5n^2 + n + 5 as O(n2)O(n^2).

This is true from the definition:

  • We can always find a value of cc that is larger than a constant factor: 2n≤c⋅n2n \le c \cdot n with c≥2c \ge 2.
  • We can always find a value of cc that outgrows the smaller terms: n2+n≤c⋅n2n^2 + n \le c \cdot n^2 with c≥2c \ge 2 and n≥1n \ge 1.

More examples

O(1), constant

Print the first
Python
def print_first(nums: list[int]) -> None:
print(nums[0])
print_first([5, 2, 8, 1, 9])

O(log n), logarithmic

Print the halves
Python
def print_halves(n: int) -> None:
while n > 0:
print(n)
n //= 2
print_halves(8)

O(n), linear

Print every number
Python
def print_all(nums: list[int]) -> None:
for num in nums:
print(num)
print_all([5, 2, 8, 1, 9])

O(n log n), linearithmic

Print the doublings
Python
def print_doublings(n: int) -> None:
for i in range(n):
j = 1
while j < n:
print(i, j)
j *= 2
print_doublings(4)

O(n²), quadratic

Print every pair
Python
def print_pairs(nums: list[int]) -> None:
for first in nums:
for second in nums:
print(first, second)
print_pairs([5, 2, 8, 1, 9])

O(2ⁿ), exponential

Branch twice
Python
def branch(n: int) -> None:
print(n)
if n > 0:
branch(n - 1)
branch(n - 1)
branch(2)

Quiz

What is the time complexity?

Has zero
Python
def has_zero(nums: list[int]) -> bool:
for num in nums:
if num == 0:
return True
return False
function hasZero(nums) {
for (const num of nums) {
if (num === 0) return true
}
return false
}
static boolean hasZero(int[] nums) {
for (int num : nums) {
if (num == 0) return true;
}
return false;
}

What is the time complexity?

Pairs with a sum
Python
def count_pairs(nums: list[int], target: int) -> int:
count = 0
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
count += 1
return count
function countPairs(nums, target) {
let count = 0
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) count++
}
}
return count
}
static int countPairs(int[] nums, int target) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) count++;
}
}
return count;
}

What is the time complexity?

Halvings
Python
def halvings(n: int) -> int:
steps = 0
while n > 1:
n //= 2
steps += 1
return steps
function halvings(n) {
let steps = 0
while (n > 1) {
n = Math.floor(n / 2)
steps++
}
return steps
}
static int halvings(int n) {
int steps = 0;
while (n > 1) {
n /= 2;
steps++;
}
return steps;
}

What is the space complexity?

Squares
Python
def squares(nums: list[int]) -> list[int]:
return [num * num for num in nums]
function squares(nums) {
return nums.map(num => num * num)
}
static int[] squares(int[] nums) {
return Arrays.stream(nums).map(num -> num * num).toArray();
}
Was this lesson helpful?