The first line and the return run once each, and the three lines inside the loop run times each.
So the total number of operations is .
In Big O notation, we can say that the time complexity is .
This is because with and , the line is never below for any .
So we found at least one pair of and for which stays above .
f(n) = 3n + 2
c·n = 4n
In general, you can always drop constant factors and smaller terms.
operations is written as , and as .
This is true from the definition:
We can always find a value of that is larger than a constant factor: with .
We can always find a value of that outgrows the smaller terms: with and .
More examples
O(1), constant
Print the first
Python
1defprint_first(nums: list[int]) -> None:
2print(nums[0])
3
4
5print_first([5,2,8,1,9])
O(log n), logarithmic
Print the halves
Python
1defprint_halves(n: int) -> None:
2while n >0:
3print(n)
4 n //=2
5
6
7print_halves(8)
O(n), linear
Print every number
Python
1defprint_all(nums: list[int]) -> None:
2for num in nums:
3print(num)
4
5
6print_all([5,2,8,1,9])
O(n log n), linearithmic
Print the doublings
Python
1defprint_doublings(n: int) -> None:
2for i inrange(n):
3 j =1
4while j < n:
5print(i, j)
6 j *=2
7
8
9print_doublings(4)
O(n²), quadratic
Print every pair
Python
1defprint_pairs(nums: list[int]) -> None:
2for first in nums:
3for second in nums:
4print(first, second)
5
6
7print_pairs([5,2,8,1,9])
O(2ⁿ), exponential
Branch twice
Python
1defbranch(n: int) -> None:
2print(n)
3if n >0:
4branch(n -1)
5branch(n -1)
6
7
8branch(2)
Quiz
What is the time complexity?
Has zero
Python
1defhas_zero(nums: list[int]) -> bool:
2for num in nums:
3if num ==0:
4returnTrue
5returnFalse
1functionhasZero(nums){
2for(constnumof nums){
3if(num ===0)returntrue
4}
5returnfalse
6}
1staticbooleanhasZero(int[]nums){
2for(intnum : nums){
3if(num ==0)returntrue;
4}
5returnfalse;
6}
The loop can stop early, but in the worst case there is no zero and it visits every element, so the answer is O(n).
The inner loop starts after i, so it runs , then , and so on down to 0 times. That adds up to . Dropping the constant factor and the smaller term leaves O(n²).
What is the time complexity?
Halvings
Python
1defhalvings(n: int) -> int:
2 steps =0
3while n >1:
4 n //=2
5 steps +=1
6return steps
1functionhalvings(n){
2letsteps=0
3while(n >1){
4 n = Math.floor(n /2)
5 steps++
6}
7return steps
8}
1staticinthalvings(intn){
2intsteps=0;
3while(n >1){
4 n /=2;
5 steps++;
6}
7return steps;
8}
Each pass halves n, so the loop makes passes in total.
What is the space complexity?
Squares
Python
1defsquares(nums: list[int]) -> list[int]:
2return[num * num for num in nums]
1functionsquares(nums){
2return nums.map(num=> num * num)
3}
1staticint[]squares(int[]nums){
2returnArrays.stream(nums).map(num -> num * num).toArray();
3}
The function builds a new array with one value for every element of the input, so the memory it uses grows linearly.