Lesson 39 of 50 intermediate

Time Complexity — Making Your Code Fast

Why some solutions pass and others get TLE — the secret is Big O!

Open interactive version (quiz + challenge)

Real-world analogy

Time complexity is like choosing how to travel from your house to school. Walking is O(n) — it takes a while. Biking is O(n/2) — faster! A car is O(log n) — much faster! A helicopter is O(1) — instant! For the same destination (same problem), different methods take vastly different times. Choosing the right 'vehicle' (algorithm) is everything!

What is it?

Time complexity is a way to measure how fast an algorithm is by counting how the number of operations grows as the input gets bigger. We use Big O notation — O(1), O(n), O(n log n), O(n²), etc. Understanding time complexity is crucial for competitive programming because it tells you whether your solution will pass within the time limit before you even submit it!

Real-world relevance

Google searches billions of web pages in milliseconds because they use O(1) lookups (hash tables) and O(log n) searches. If they used O(n) search, looking through billions of pages would take minutes! Amazon's recommendation system, GPS navigation, and even Netflix's movie suggestions all depend on fast algorithms with good time complexity.

Key points

Code example

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; i++) cin >> a[i];
    
    // O(1) — Constant: always same number of operations
    cout << "First element: " << a[0] << "\n";
    
    // O(n) — Linear: one loop through all elements
    long long sum = 0;
    for (int i = 0; i < n; i++) sum += a[i];
    cout << "Sum: " << sum << "\n";
    
    // O(n log n) — Sorting
    sort(a.begin(), a.end());
    cout << "Sorted min: " << a[0] << " max: " << a[n-1] << "\n";
    
    // O(n^2) — Two nested loops (SLOW for large n!)
    // Count pairs with equal values
    int pairCount = 0;
    if (n <= 5000) {  // Only safe for small n!
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (a[i] == a[j]) pairCount++;
            }
        }
    }
    cout << "Equal pairs: " << pairCount << "\n";
    
    // O(n) way to count equal pairs (SMART!)
    // After sorting, count consecutive equal elements
    int smartCount = 0;
    int i = 0;
    while (i < n) {
        int j = i;
        while (j < n && a[j] == a[i]) j++;
        int groupSize = j - i;
        smartCount += groupSize * (groupSize - 1) / 2;  // Choose 2 from group
        i = j;
    }
    cout << "Equal pairs (fast): " << smartCount << "\n";
    
    return 0;
}

Line-by-line walkthrough

  1. 1. We read an array of n integers — this is the standard CP input pattern.
  2. 2. cout << a[0] — accessing one element is O(1). No matter how big the array, getting one element is instant.
  3. 3. The sum loop: for (int i = 0; i < n; i++) sum += a[i]; — we visit each element exactly once, so it's O(n). If n doubles, the time doubles.
  4. 4. sort(a.begin(), a.end()); — C++'s built-in sort is O(n log n). It's one of the most commonly used operations in CP. After sorting, the smallest is at a[0] and largest at a[n-1].
  5. 5. The double loop for counting pairs: two nested loops each going up to n, so the inner loop runs roughly n²/2 times total. That's O(n²). We guard it with if (n <= 5000) to prevent TLE.
  6. 6. The SMART O(n) approach: after sorting, equal elements are next to each other. We count each group's size and use the formula groupSize * (groupSize - 1) / 2 (combinations of 2 from the group). This replaces O(n²) with O(n)!
  7. 7. groupSize * (groupSize - 1) / 2 — this is the combination formula 'n choose 2', which counts how many pairs you can make from groupSize elements. Math saves the day!

Spot the bug

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    int a[n];
    for (int i = 0; i < n; i++) cin >> a[i];
    
    // Find if any two elements sum to 1000000
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (a[i] + a[j] == 1000000) {
                cout << "YES\n";
                return 0;
            }
        }
    }
    cout << "NO\n";
    return 0;
}
Need a hint?
Two bugs! First, look at the inner loop — can j equal i? Should an element be paired with itself? Second, what's the time complexity, and will this pass if n = 100,000?
Show answer
Bug 1: j starts at 0, so when i==j, we pair an element with ITSELF. If a[i] = 500000, then a[i]+a[i] = 1000000 and we'd incorrectly say YES even though there's only ONE 500000 in the array. Fix: start j at i+1. Bug 2: with n=100,000, this O(n²) solution does 10 BILLION operations — it will TLE! A faster approach: sort the array, then use two pointers (one at start, one at end) moving inward. That's O(n log n).

Explain like I'm 5

Imagine you're looking for your friend in a group of people. If there are 10 people, you can check each one quickly. But what if there are a MILLION people? Checking one by one takes a while. Checking every pair takes FOREVER. But if everyone is sorted by name, you can use a trick like opening a phone book to the middle and narrowing down — super fast! Figuring out how fast or slow a way of solving something is — that is what this lesson is all about. Always pick the smartest way to find your friend!

Fun fact

The difference between O(n) and O(n²) is MASSIVE at scale. For n = 1,000,000: O(n) = 1 million operations (0.01 seconds), O(n²) = 1 TRILLION operations (about 3 hours!). That's the difference between a blink and a nap! The biggest improvements in computing history weren't faster hardware — they were better algorithms with better Big O!

Hands-on challenge

You're given an array of n numbers and need to find if any two numbers sum to a target value k. The O(n²) approach checks all pairs. Can you think of an O(n log n) approach? Hint: sort the array first, then for each element a[i], binary search for (k - a[i]). Code both solutions and test them! For n=100000, the O(n²) version would be too slow but the O(n log n) version flies!

More resources

Open interactive version (quiz + challenge) ← Back to course: CP Zero to Hero