notes

Table of contents generated with markdown-toc

Definition

Time complexity - a way of showing how the runtime of a function increases as the size of the input increases

time complexity types:

How to count time complexity?

  1. write down the function formally
  2. find the fastest growing term
  3. take out the coefficient

In computer science you tend to care more about larger input than smaller input.

Time complexity types

Constant

arr = [1, 4, 3, 2, ..., 10]

def stupid_function(arr):
	total = 0  # O(1)
	return total  # O(1)

Theoretically

T = O(1) + O(1) = c1 + c2 = c3 = c3 * 1 = O(1)

O(1) + O(1) = O(1)

By an experiment

T = c = 0.115 * 1 = c1 * 1 = O(1)

Linear

given_array = [1, 4, 3, 2, ..., 10]

def find_sum(given_array):
    total = 0  # O(1)
    for i in given_array:  # O(n)
        total += 1  # O(1)
    return total  # O(1)

Theoretically

T = O(1) + n * O(1) + O(1) = c1 + n * c2 = O(n)

By the experiment

T = an + b = c1 * n + c2 = O(n)

Quadratic

array_2d = [
	[1, 4, 3],
	[5, 3, 2],
	[6, 1, 2]
]  # n^2

def find_sum_2d(array_2d):
	total = 0  # O(1)
	for row in array_2d:  # O(n)
		for i in row:  # O(n)
			total += i  # O(1)
	return total  # O(1)

Theoretically:

T = O(1) + n2 * (n…O(1)) + O(1) = c1 + n2 * c2 = O(n2)

By the experiment

T = cn2 + dn + e = c1 * n2 + c2 * n + c3 = n2 + n = O(n2)

What if there is an execution of two double loops in a function?

def find_sum_2d(array_2d):
    total = 0  # O(1)
    for row in array_2d:  # O(n)
        for i in row:  # O(n)
            total += i  # O(1)

    for row in array_2d:  # O(n)
        for i in row:  # O(n)
            total += i  # O(1)
            
    return total  # O(1)

T = O(2n2) = O(n2)

Q: why?

A: In Big O notation, constants are ignored. So, when we say O(2n2)O(2n2), we can drop the constant factor 2 because it doesn’t significantly affect the growth rate of the function as nn approaches infinity.

T = 2n2 * c + … = 2n2 * c + c2n + c3a = (2c) * n2 + c2n + 3 = O(n2)