⏳ Time Complexity ⏳ and ๐ŸŒŒ Space Complexity ๐ŸŒŒ

 Follow Me

✅ What is Time Complexity?

Time Complexity is the measure of how the execution time of an algorithm grows relative to the input size (n).

It tells us how fast an algorithm is.

๐Ÿ”น Common Time Complexities:

Big-O NotationNameDescription
O(1)Constant TimeTime doesn't grow with input size
O(log n)LogarithmicTime grows slowly as input increases
O(n)LinearTime grows directly with input
O(n log n)LinearithmicTime grows faster than linear but less than quadratic
O(n²)QuadraticTime grows with the square of input size
O(2โฟ)ExponentialTime doubles with each addition to input size
O(n!)FactorialTime grows extremely fast (used in permutations etc.)

๐Ÿง  Example in Python (Time Complexity O(n)):

def find_max(arr): max_num = arr[0] for num in arr: if num > max_num: max_num = num return max_num
  • Here, the function iterates once over the array → O(n) time.




✅ What is Space Complexity?

Space Complexity refers to the amount of memory used by an algorithm as a function of the input size.

It includes both temporary variables and recursive stack space.

๐Ÿ”น Common Space Complexities:

Big-O NotationDescription
O(1)Uses constant space
O(n)Uses space proportional to input
O(n²)Uses space for matrices or nested structures

๐Ÿง  Example in Python (Space Complexity O(n)):

def duplicate_list(arr): new_list = [] for item in arr: new_list.append(item) return new_list
  • Here, the function creates a new list of the same size → O(n) space.


๐Ÿ”„ Key Differences: Time vs Space Complexity

FeatureTime ComplexitySpace Complexity
DefinitionMeasures execution time growthMeasures memory usage growth
Concerned withCPU usageMemory/RAM usage
Example MetricLoops, recursion, function callsVariables, data structures, call stack
GoalOptimize speedOptimize memory usage
Common Trade-offMore speed can cost more memory (vice versa)Use memoization: faster but more space



๐Ÿ“Œ How to Analyze Time and Space Complexity in Python?

๐Ÿ”น Step-by-Step:

  1. Count the Loops – Each nested loop adds a layer to time complexity.

  2. Check Recursive Depth – For recursion, count calls and stack usage.

  3. Track Memory Allocation – New lists, sets, dicts use memory.

  4. Ignore Constants – Big-O ignores low-level constants.


๐Ÿงช Examples with Both Time and Space Complexity

✅ Example 1: Linear Search

def linear_search(arr, target): for i in range(len(arr)): if arr[i] == target: return i return -1
  • Time Complexity: O(n) → worst case checks every element.

  • Space Complexity: O(1) → no extra space.

✅ Example 2: Merge Sort (Recursive)

def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right) def merge(left, right): result = [] while left and right: result.append(left.pop(0) if left[0] < right[0] else right.pop(0)) result.extend(left + right) return result
  • Time Complexity: O(n log n)

  • Space Complexity: O(n) → due to the result and recursion stack.

✅ Example 3: Fibonacci (Recursive vs Dynamic)

❌ Naive Recursion:

def fib(n): if n <= 1: return n return fib(n-1) + fib(n-2)
  • Time: O(2โฟ), Space: O(n)

✅ Memoization (Dynamic Programming):

def fib(n, memo={}): if n in memo: return memo[n] if n <= 1: return n memo[n] = fib(n-1, memo) + fib(n-2, memo) return memo[n]
  • Time: O(n), Space: O(n)


๐Ÿงพ Summary Table

AlgorithmTime Complexity    Space Complexity
Linear SearchO(n)    O(1)
Binary SearchO(log n)    O(1)
Bubble SortO(n²)    O(1)
Merge SortO(n log n)    O(n)
Quick SortO(n log n) avg    O(log n)
Fibonacci (Rec)O(2โฟ)    O(n)
Fibonacci (Memo)O(n)    O(n)


๐Ÿ’ก Bonus Tip: Use Python's time and sys modules to measure

import time import sys start = time.time() # your_function() print("Time:", time.time() - start) print("Memory:", sys.getsizeof(your_object))



No comments:

Post a Comment

DSA using Python: Assignment - 2: Classes and Objects

Follow Me “In this assignment, we will learn how to use Python classes and objects to build reusable and structured code. The tasks cover re...