</>
Skip to content
DSA lessons (5/55)

DSA — Big O Notation

What is Big O?

Big O notation describes the upper bound of an algorithm's growth rate.

Big O Examples

# O(1) - Constant Time
def get_value(arr, index):
    return arr[index]

# O(log n) - Logarithmic
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

# O(n) - Linear
def linear_search(arr, target):
    for i, val in enumerate(arr):
        if val == target:
            return i
    return -1

# O(n²) - Quadratic
def selection_sort(arr):
    for i in range(len(arr)):
        min_idx = i
        for j in range(i + 1, len(arr)):
            if arr[j] < arr[min_idx]:
                min_idx = j
        arr[i], arr[min_idx] = arr[min_idx], arr[i]

Growth Rate Comparison

nO(1)O(log n)O(n)O(n log n)O(n²)
110101
10131033100
1001710066410,000
1000110100099661,000,000

Rules for Big O

  1. Drop constants: O(2n) → O(n)
  2. Drop lower-order terms: O(n² + n) → O(n²)
  3. Different inputs = different variables

Mini Practice

  1. Determine Big O of simple functions
  2. Analyze nested loops
  3. Compare algorithm efficiencies
  4. Optimize for better Big O

Up Next

Continue with Recursion — recursive problem solving.

Related Topics

Frequently Asked Questions about Big O Notation

What is Big O Notation in DSA?

Big O Notation is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Big O Notation?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Big O Notation.

Why is Big O Notation important in DSA?

Big O Notation is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.