Skip to main content

complexity

Time Complexity

Time complexity is defined as the amount of time taken by an algorithm to run, as a function of the length of the input

Example

def sum(arr):
sum = 0
for x in arr:
sum = sum + x
return sum

The time complexity = O(n)

Common Types

img

img

Common Sorts

AlgorithmBest Case Time ComplexityAverage Case Time ComplexityWorst Case Time Complexity
Linear SearchO(1)O(n)O(n)
Binary SearchO(1)O(log n)O(log n)
Bubble SortO(n)O(n²)O(n²)
Selection SortO(n²)O(n²)O(n²)
Insertion SortO(n)O(n²)O(n²)
Merge SortO(n log n)O(n log n)O(n log n)
Quick SortO(n log n)O(n log n)O(n²)
Heap SortO(n log n)O(n log n)O(n log n)
Bucket SortO(n+k)O(n+k)O(n²)
Radix SortO(nk)O(nk)O(nk)
Tim SortO(n)O(n log n)O(n log n)
Shell SortO(n)O((n log n)²)O(n²)

Space Complexity

Space complexity refers to the total amount of memory space used by an algorithm/program, including the space of input values for execution

In the interview, we rarely count the space of input values. However, we're better ask the interviewer.

Example

def sum(arr):
sum = 0
for x in arr:
sum = sum + x
return sum

The space complexity = O(1) ~ constant