|2. Time & Space Complexity
Chapter 2DSA (Data Structures & Algorithms)~1 min read

Time & Space Complexity

Big O Notation शिका

Big O Notation हे algorithm किती वेळ घेतो ते measure करण्याची पद्धत आहे. Input size n वाढला तर time/space किती वाढतं — हे Big O सांगतो. Interviews मध्ये नेहमी "Time complexity काय?" विचारतात.

Common Big O complexities

O(1) — Constant time

python
# O(1) — n काहीही असो, same time
def get_first(arr):
    return arr[0]  # directly index access

# Example: array indexing, hash table lookup

O(n) — Linear time

python
# O(n) — n वाढला तर proportionally time वाढतो
def find_max(arr):
    max_val = arr[0]
    for num in arr:     # n times loop
        if num > max_val:
            max_val = num
    return max_val

# n=10 → 10 steps, n=1000 → 1000 steps

O(n²) — Quadratic time

python
# O(n²) — nested loops
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):          # n times
        for j in range(n-1-i):  # n times
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]

# n=10 → 100 steps, n=100 → 10000 steps — slow!

O(log n) — Logarithmic time

python
# O(log n) — प्रत्येक step मध्ये problem half होतो
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1
# n=1000 → फक्त ~10 steps!
  • O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ)
  • O(1) best, O(2ⁿ) worst
  • Space complexity = extra memory वापर
  • Best/Average/Worst case — Big O नेहमी worst case

Key Points — लक्षात ठेवा

  • Big O = algorithm efficiency measure
  • O(1) — constant, O(n) — linear, O(n²) — quadratic
  • O(log n) — binary search, O(n log n) — merge sort
  • Nested loops = multiply complexities
  • Space complexity = extra memory used
0/10 chapters पूर्ण