<< back to Guides

πŸ“ˆ Big O Notation: Writing Efficient Algorithms

Big O Notation is a way to describe the upper bound of an algorithm’s time or space complexity as a function of the input size n. It helps developers measure scalability, performance, and make informed choices.


πŸ”Ή O(1) – Constant Time

Examples:

arr[5] // Access element at index
hashMap.put(key, value) // Insert in hash map

βœ… Use Case: Hash table lookup, setting a value in a fixed-size array.


πŸ”Ή O(n) – Linear Time

Examples:

for (int i = 0; i < n; i++) {
    sum += arr[i];
}

βœ… Use Case: Looping through an array or list.


πŸ”Ή O(log n) – Logarithmic Time

Examples:

// Binary Search
int binarySearch(int[] arr, int target) {
    int low = 0, high = arr.length - 1;
    while (low <= high) {
        int mid = (low + high) / 2;
        if (arr[mid] == target) return mid;
        else if (arr[mid] < target) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}

βœ… Use Case: Binary search, operations on balanced BSTs.


πŸ”Ή O(n log n) – Linearithmic Time

Examples:

Merge Sort, Quick Sort, Heap Sort

βœ… Use Case: Large-scale data sorting.


πŸ”Ή O(nΒ²) – Quadratic Time

Examples:

for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        // Do something
    }
}

βœ… Use Case: Simple comparison-based sorting, brute-force string comparison.


πŸ”Ή O(nΒ³) – Cubic Time

Examples:

// Naive matrix multiplication
for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
        for (int k = 0; k < n; k++)
            C[i][j] += A[i][k] * B[k][j];

βœ… Use Case: Dense matrix multiplication.


πŸ”Ή O(√n) – Square Root Time

Examples:

// Check for prime numbers
for (int i = 2; i <= sqrt(n); i++) {
    if (n % i == 0) return false;
}

βœ… Use Case: Sieve of Eratosthenes, divisibility checks.


πŸ”Ή O(2ⁿ) – Exponential Time

Examples:

// Fibonacci Recursive
int fib(int n) {
    if (n <= 1) return n;
    return fib(n-1) + fib(n-2);
}

❌ Avoid unless input is very small.


πŸ”Ή O(n!) – Factorial Time

Examples:

// Generating permutations of an array

❗ Warning: Explodes with small increases in input size.


πŸ“Š Big O Comparison Chart

Big O Input Size 10 Input Size 100
O(1) 1 1
O(log n) ~3 ~7
O(n) 10 100
O(n log n) ~30 ~700
O(nΒ²) 100 10,000
O(2ⁿ) 1024 Huge
O(n!) 3.6M Massive

🧠 Final Tips

<< back to Guides