Time and space complexity

Time and Space Complexity – Cheat Sheet

Time and space complexity
Time and space complexity

What is time complexity?

Time complexity is a measure of how the running time of an algorithm increases as the input size increases. It indicates the number of steps the algorithm takes based on the input. Since every computer takes a different time to perform computation, we need a standard mechanism to measure the speed of computation, which is given by time complexity. It measures how fast the number of operations increases as inputs get bigger.

What is space complexity?

Space complexity is the amount of memory or space the algorithm takes to run as a function of input size. It includes:

  • fixed parts -> which are the constants, program instructions, and variables
  • variable part -> which includes memory of data structures used, stacks, function calls, and temporary variables.

Common Time Complexities

Use caseComplexity
constantO(1)
binary search, divide and conquerO(log n)
traversing array/ listO(n)
merge sort, quick sortO(n log n)
nested loops, bubble sortO(n2 )
matrix multiplicationO(n3 )
recursive fibonnacci, subset generationO(2n )
travelling salesmanO(n!)

Data Structure Operations:

Data StructureInsertSearchDelete
Array (Sorted)O(n)O(log n)O(n)
Array (Unsorted)O(1)O(n)O(n)
Linked ListO(1) (at head)O(n)O(n)
Stack/QueueO(1)O(1)O(1)
Hash TableO(1) (avg)O(1) (avg)O(1) (avg)
BST (balanced)O(log n)O(log n)O(log n)
BST (skewed)O(n)O(n)O(n)
HeapO(log n)O(1)O(log n)

Sorting Algorithms:

AlgorithmBest Case ComplexityWorst Case ComplexityAverage Case ComplexitySpace Complexity
Bubble SortO(n)O(n2 )O(n2 )O(1)
Insertion SortO(n)O(n2 )O(n2 )O(1)
Selection SortO(n2 )O(n2 )O(n2 )O(1)
Merge SortO(n log n)O(n log n)O(n log n)O(n)
Heap SortO(n log n)O(n log n)O(n log n)O(1)
Quick SortO(n log n)O(n log n)O(n2 )O(log n)

Loop Patterns:

Use CaseComplexity
Simple LoopO(n)
Multiply StepO(log n)
Nested LoopsO(n2 )
Triangular Nested Loops O(n2 )
Logarithmic Inner LoopO(n log n)

Share

Leave a Reply

Your email address will not be published. Required fields are marked *