AlgoMaster Logo

Time Complexity Patterns

High Priority15 min readUpdated December 5, 2026
Listen to this chapter
Unlock Audio

Time Complexity Patterns

When you look at a piece of code, you can often determine its time complexity by understanding how the code is structured.

  • How many loops are there?
  • Do they run one after another, or are they nested inside each other?
  • How does the loop variable change with each iteration?
  • And if the function is recursive, how many recursive calls does it make, and how much work happens in each call?

In this lesson, we'll explore the most common time complexity patterns you'll encounter when solving DSA problems and preparing for coding interviews.

1. Constant Time: O(1)

Let's start with the simplest pattern: constant time.

Here's a function that calculates the sum of all integers from 1 to n.

Instead of looping through each number, it uses a mathematical formula that requires just one addition, one multiplication, and one division.

Whether n is 10 or 10 million, the function performs exactly the same amount of work. So its time complexity is O(1).

Let's look at a few other common operations that run in constant time.

Accessing an array element by its index takes O(1) time. That's because the element's memory address can be calculated directly from its index.

Looking up a key in a hash map also takes O(1) time on average. A hash function helps determine which bucket contains the key. The lookup goes directly to that bucket instead of scanning the entire collection.

Loading simulation...

Remember, O(1) doesn't mean the code performs just one operation. It means the amount of work remains constant, regardless of how large the input becomes.

2. Linear Time: O(n)

Now let's return to our earlier example of calculating the sum from 1 to n, but this time, let's use a loop.

The loop goes through every number from 1 to n, so it runs n times. During each iteration, it performs a constant amount of work, including an addition and an assignment.

The total work is therefore proportional to n, giving us a time complexity of O(n). This is known as linear time. If you double the input size, the amount of work roughly doubles.

Loading simulation...

This is one of the most common time complexity patterns you'll encounter. Finding the maximum element in an array and checking whether a string is a palindrome are both examples of this pattern.

There are also a few variations that still result in linear time.

If the loop advances two steps at a time instead of one, it runs roughly n/2 times. After dropping the constant factor, we're still left with O(n).

Similarly, if a function contains two separate loops that traverse the same array, one after the other, the total work is proportional to 2n, which also simplifies to O(n).

As long as we make a fixed number of passes over the input and perform a constant amount of work per iteration, the time complexity remains linear.

3. Multiple Inputs: O(n + m)

Some functions work with multiple independent inputs. Here's a function that calculates the sum of all elements in two arrays, a and b.

The first loop goes through array a, which contains n elements. Once it finishes, the second loop goes through array b, which contains m elements.

Since the loops run one after the other, we add the amount of work they perform. The total work is proportional to n + m, giving us a time complexity of O(n + m).

Loading simulation...

We can't simplify this to O(n) because n and m are independent input sizes. Array b could contain 10 elements or 10 million, regardless of the size of array a. That's why we need to keep both input sizes in our complexity expression.

If one loop were nested inside the other, we would multiply their work instead, giving us O(n × m).

And, that brings us to nested loops.

4. Nested Loops: O(n²)

Here's a function that prints every ordered pair of elements in an array.

The outer loop selects the first element of the pair using index i. For each value of i, the inner loop iterates through all n possible values of j.

So for each of the n outer iterations, we perform n units of work. That's n multiplied by n, giving us a time complexity of O(n²). This is known as quadratic time.

Loading simulation...

If you double the input size, the amount of work becomes four times larger.

In general, if each loop runs n times, two nested loops give us O(n²), while three nested loops give us O(n³).

But what happens when the inner loop doesn't go through the entire input on every iteration of the outer loop?

5. Shrinking Inner Loops: Still O(n²)

Here's a function that checks whether an array contains duplicates by comparing every distinct pair of elements.

In the worst case, the array contains no duplicates, so the function must examine every pair before returning false.

Let's count how many comparisons it performs. When i is 0, the inner loop runs n - 1 times. When i is 1, it runs n - 2 times. This pattern continues until there are no remaining elements to compare.

Adding these together, we get (n - 1) + (n - 2) + ... + 0. The sum is n(n - 1) / 2, which expands to n²/2 - n/2. After dropping the constant factor and the lower-order term, we're left with O(n²).

Loading simulation...

Notice that even though the inner loop performs fewer iterations each time, the overall time complexity is still quadratic.

Visually, the nested loops cover a triangular region that's roughly half the full square. But reducing the work by a constant factor doesn't change its asymptotic growth rate.

6. Logarithmic Time: O(log n)

Now let's look at a loop where the variable grows by a constant factor instead of a fixed amount.

Here, i doubles with each iteration, going from 1 to 2, 4, 8, 16, and so on. How many iterations does it take to reach n?

After k iterations, the value of i is 2ᵏ. The loop stops when this value reaches or exceeds n. Solving for k gives us approximately log₂ n. So the loop runs roughly log n times, giving us a time complexity of O(log n).

The same pattern appears when a variable starts at n and gets divided by two on every iteration.

Here, i starts at 64 and goes down to 32, 16, 8, 4, 2, and finally 1.

After k iterations, the value of i is approximately n / 2ᵏ. Reaching 1 again takes about log₂ n iterations.

A loop doubling i from 1 and a loop halving i from 64 both take 6 iterations: i = 2ᵏ ≥ n and n / 2ᵏ = 1 give k = log₂ n, O(log n), and n = 1,000,000 needs only about 20

What's interesting about logarithmic time is how slowly it grows. Even with an input size of one million, the loop runs only about 20 times.

One of the most common examples of logarithmic time is binary search. Here, we're trying to find a target value in a sorted array.

On each iteration, we examine the middle element of the current search range. If it matches the target, we return its index. Otherwise, we use the sorted order of the array to eliminate the half where the target cannot exist.

Each iteration performs a constant amount of work while reducing the remaining search range by half. In the worst case, this takes roughly log n iterations, giving us a time complexity of O(log n).

7. Linearithmic Time: O(n log n)

Now let's combine two patterns we've already seen.

The outer loop runs n times. For each iteration of the outer loop, the inner loop repeatedly doubles j until it reaches n, which takes roughly log n steps.

Since the inner loop starts over and runs to completion for every iteration of the outer loop, we multiply their iteration counts. This gives us a time complexity of O(n log n).

Loading simulation...

n log n grows faster than linear time, but much more slowly than quadratic time. For example, when n is one million, n log n is roughly 20 million, while n² is one trillion.

Sorting

In practice, one of the most common places you'll encounter n log n time complexity is in sorting. Efficient comparison-based sorting algorithms like merge sort and heap sort run in O(n log n) time.

Let's use merge sort to understand where this complexity comes from.

Merge sort repeatedly divides the array in half until each piece contains a single element, creating roughly log n levels.

Loading simulation...

At each level, merging the smaller sorted pieces back together requires a total of O(n) work. With O(n) work at each of the log n levels, we get an overall time complexity of O(n log n).

8. Exponential Time: O(2ⁿ)

So far, we've looked at examples involving loops. When it comes to recursion, we need a slightly different approach.

One way to analyze a recursive function is to visualize its recursion tree. Each node represents a function call, and its children represent the recursive calls that function makes.

If each call performs a constant amount of work apart from its recursive calls, we can determine the time complexity by counting the total number of nodes in the tree.

Let's look at a function that calculates the nth Fibonacci number.

Every non-base-case call to fib(n) makes two recursive calls: fib(n - 1) and fib(n - 2). These calls continue branching until they reach a base case, where n is either 0 or 1.

Starting with a single call at the root, the number of calls can double at each level. Since the longest path reduces n by one at each step, the recursion tree has roughly n levels.

Loading simulation...

With up to twice as many nodes at each successive level, the total number of calls grows exponentially and is bounded by a constant multiple of 2ⁿ. This gives us a time complexity of roughly O(2ⁿ).

The branches that call fib(n - 2) reach the base case sooner, so the recursion tree isn't completely full. The actual number of calls grows roughly as 1.62ⁿ. That's still exponential growth, and O(2ⁿ) remains a valid upper bound.

With exponential growth, increasing n by just one multiplies the amount of work by roughly a constant factor. 2³⁰ is already over a billion.

Memoization

The reason this Fibonacci implementation is so inefficient is that it repeatedly calculates the same Fibonacci numbers across different branches of the recursion tree.

By storing each result the first time we calculate it, a technique known as memoization, we only need to compute each value from 0 to n once, reducing the time complexity to O(n).

The general rule

More generally, if each call makes at most b recursive calls, where b is greater than one, and the recursion goes d levels deep, the total number of calls is O(bᵈ).

Another common example of exponential growth is generating all subsets of an array. For each element, we have two choices: either include it in the subset or leave it out. With n elements, this gives us 2ⁿ possible subsets.

9. Factorial Time: O(n!)

The final pattern is factorial time, which commonly appears in problems that involve generating all possible permutations of a set of elements.

For the first position, we have n choices. Once we choose an element, we're left with n - 1 choices for the second position, n - 2 for the third, and so on.

Multiplying these choices together gives us n × (n - 1) × (n - 2) × ... × 1. This is n factorial.

Since constructing and printing each permutation takes O(n) time, the overall time complexity is O(n × n!) for this problem.

Permutations of 4 elements: 4 × 3 × 2 × 1 = 24 = 4!, and printing each one takes n steps, 24 × 4 = 96, O(n × n!); 10! = 3,628,800 and 20! = 2,432,902,008,176,640,000

Factorial growth is even faster than exponential growth. 10! is already around 3.6 million, while 20! exceeds two quintillion.

10. Working Backward from Constraints

Understanding these patterns also helps you work backward from a problem's constraints.

As a rough rule of thumb, a computer can perform around one hundred million simple operations per second, although this number is often much lower in languages like Python.

  • If n is around 20 or less, an O(2ⁿ) solution might be practical.
  • If n is a few thousand, an O(n²) solution is often fast enough.
  • When n reaches a hundred thousand or a million, you'll generally need an O(n log n) or O(n) solution.
  • And if n can be as large as one billion, you'll typically need something like O(log n), or a constant-time formula.
Constraints of 1 ≤ n ≤ 100,000 point to O(n log n) and an algorithm like sorting: n ≤ 20 allows O(2ⁿ), a few thousand allows O(n²), 100,000 to 1,000,000 needs O(n log n) or O(n), and 1,000,000,000 needs O(log n) or O(1), at about 100,000,000 operations per second

So before you start writing code, look at the input constraints, estimate which time complexities are likely to fit within the time limit, and use that information to narrow down your choice of algorithms.