Skip to content
Visual explainer 3h to learn 3 steps

Big-O, time & space complexity

State the complexity of any solution you write.

By Invicly Tech, , in Interview Preparation. About 11 minutes to read.

Topic 1 of 27

In short

Big-O describes how an algorithm's time or memory grows as the input size n grows. Interviewers expect you to state it for every solution and to compare options by it.

Think of it like this: Big-O is the shape of the cost curve, not the exact stopwatch time.

Explained simply

Big-O is a way to describe how much work a program does as its input gets bigger. We do not count seconds, because seconds depend on the computer. We count how the number of steps grows. If doubling the input doubles the work, that is O(n). If doubling the input makes the work four times bigger, that is O(n squared).

Imagine looking for a name in a phone book. Reading every page is O(n). Opening the book in the middle, then the middle of the correct half, and so on, is O(log n). Both find the name, but with a million pages the first takes a million looks and the second takes about twenty.

In interviews, Big-O is how you compare ideas before writing code. You describe a brute-force solution, say its cost, then improve it. Interviewers want to hear both time (how many steps) and space (how much extra memory). Saying "O(n) time, O(n) space because of the hash set" is a complete answer.

You do not need heavy maths. A few rules cover nearly every problem: loops one after another add, loops inside loops multiply, halving the input each step gives log n, and a recursive function costs roughly the number of calls times the work done in each call.

Press Play on a diagram to walk through it one step at a time.

FlowHow to analyse a solution
  1. 1
    Define n

    Name what grows: array length, nodes, string size

  2. 2
    Count loop work

    One pass is O(n); nested passes multiply

  3. 3
    Count recursion

    Roughly branches to the power of depth

  4. 4
    Drop constants

    O(2n + 5) simplifies to O(n)

  5. 5
    Keep dominant term

    O(n squared + n) simplifies to O(n squared)

  6. 6
    State extra space

    Maps, arrays, recursion stack depth

LayersGrowth rates, fastest first
  1. 1
    O(1)

    Array index, hash map lookup

  2. 2
    O(log n)

    Binary search, balanced tree lookup

  3. 3
    O(n)

    Single pass over the input

  4. 4
    O(n log n)

    Efficient sorting

  5. 5
    O(n squared)

    Comparing every pair

  6. 6
    O(2 to the n)

    Trying every subset

MapInput size hints at the target complexity
How big is n?
  • n up to 20
    • O(2^n) backtracking is fine
  • n up to 500
    • O(n^3) can pass
  • n up to 10,000
    • O(n^2) is usually fine
  • n up to 1,000,000
    • Aim for O(n log n) or O(n)
  • n above 10^9
    • Need O(log n) or O(1), often maths or binary search

In depth

Adding and multiplying loops

Two loops one after the other over the same array cost O(n) + O(n), which is still O(n). A loop inside a loop multiplies: O(n) times O(n) is O(n squared).

Watch the variable names. If you loop over array a and then over array b, the cost is O(a + b), not O(n). If you loop over b inside a loop over a, it is O(a times b). Squashing two inputs into one n hides useful detail, and interviewers notice.

An inner loop that starts at i + 1 still counts as O(n squared). It runs n - 1 times, then n - 2, and so on, which adds up to about n squared divided by 2, and we drop the constant.

  • Sequential loops: add
  • Nested loops: multiply
  • Different inputs keep different letters
  • Halving each step: log n

Counting the cost of recursion

For recursion, draw the call tree. Total time is roughly the number of calls multiplied by the work done in each call. Naive Fibonacci calls itself twice per call and goes n levels deep, so it makes about 2 to the n calls.

Merge sort splits the array in half each time, so its tree is log n levels deep. Every level touches all n elements once while merging. That gives n work times log n levels, which is O(n log n).

Space for recursion is the deepest chain of calls open at the same time, not the total number of calls. Merge sort's stack is only O(log n) deep, but its merge buffers add O(n).

MapMerge sort's call tree
Merge sort on n items
  • Level 0
    • 1 call
    • n work merging
  • Level 1
    • 2 calls of n/2
    • n work in total
  • Level 2
    • 4 calls of n/4
    • n work in total
  • log n levels
    • n work x log n levels
    • O(n log n)

Amortised cost: cheap on average over time

A Java ArrayList grows by allocating a bigger array and copying everything over when it is full. That single copy is O(n). But it happens rarely, because the capacity grows by a constant factor each time (about 1.5 times in Java).

If you add n items, the total copying work is a shrinking series that sums to O(n). Spread over n adds, each add is O(1) amortised. Amortised means "averaged over a long run of operations", not "average over random inputs". It is a guarantee about the whole sequence, which is why interviewers accept O(1) for ArrayList.add and for a queue built from two stacks.

Hidden costs that change the answer

Many wrong complexity answers come from library calls that look free. String concatenation with += in a Java loop copies the whole string each time, so building n characters that way is O(n squared); use StringBuilder. list.contains and indexOf scan the list in O(n). Sorting is O(n log n), so a solution that sorts first can never be faster than that.

Input size also hints at the expected solution. Online judges manage roughly 10 to 100 million simple steps per second, so n up to 100,000 usually needs O(n log n) or better, while n up to 20 allows trying every subset.

  • String += in a loop: O(n squared) total
  • List contains: O(n)
  • Sorting: O(n log n)
  • HashMap get and put: O(1) average
CompareBuilding a string of n characters in Java
s += c in a loop
  • New string every time
  • Copies 1 + 2 + ... + n characters
  • O(n squared) total
StringBuilder
  • Appends into a growing buffer
  • Amortised O(1) per append
  • O(n) total, toString() once

Learn it in 3 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Learn Big-O, Big-Theta and Big-Omega~1h
  2. 2
    Analyse loops and recursion costs~1h
  3. 3
    Compare time and space trade-offs~1h

Key points

  • Big-O is an upper bound, Big-Omega a lower bound, Big-Theta a tight bound.
  • Interviews usually mean worst-case Big-O unless they say average or amortised.
  • Recursion uses stack space: depth d costs O(d) memory.
  • Trading memory for speed, such as a hash set, is the most common optimisation.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
def has_dup_slow(nums):  # O(n^2) time, O(1) space
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] == nums[j]:
                return True
    return False

def has_dup_fast(nums):  # O(n) time, O(n) space
    seen = set()
    for x in nums:
        if x in seen:
            return True
        seen.add(x)
    return False

Same answer, different trade-off between time and memory.

Counting steps in three small loops

Step 1: the first loop runs n times, so it is O(n). Step 2: in the nested pair, j runs from i to n, so the inner line runs n + (n - 1) + ... + 1 = n(n + 1)/2 times, which is O(n squared). Step 3: the last loop doubles i each time, so it runs about log2(n) times. Total: O(n + n squared + log n). Keep the dominant term: O(n squared). Extra space is O(1) because we only use a few counters.

java
int work(int n) {
    int count = 0;
    for (int i = 0; i < n; i++) count++;          // n
    for (int i = 0; i < n; i++)
        for (int j = i; j < n; j++) count++;      // n(n+1)/2
    for (int i = 1; i < n; i *= 2) count++;       // about log2(n)
    return count;  // overall O(n^2) time, O(1) space
}

Merge sort, level by level

Sort 8 numbers. Level 0 has one array of 8. Level 1 has two arrays of 4, level 2 has four arrays of 2, and level 3 has eight arrays of 1. That is log2(8) = 3 levels of splitting. On the way back up, each level merges 8 elements in total, so each level costs O(n). Three levels times 8 elements gives n log n. The temporary arrays used for merging add O(n) space, and the recursion stack adds O(log n).

Quick reference

  • Sequential loops add: O(a + b). Nested loops multiply: O(a × b).
  • Halving or doubling each step gives O(log n).
  • Recursion time ≈ number of calls × work per call.
  • Recursion space = maximum call depth, not total calls.
  • Sorting costs O(n log n); a sort-first solution cannot beat that.
  • n up to 10^5 usually needs O(n log n) or better.
  • ArrayList add is O(1) amortised; inserting at index 0 is O(n).
  • Always state both time and extra space.

Common mistakes

  • Forgetting that slicing or string concatenation in a loop costs O(n) each time.
  • Ignoring recursion stack space.
  • Calling an O(n) operation like list.remove inside a loop and claiming O(n) overall.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What is the time complexity of a loop where i starts at 1 and doubles until it reaches n?

Question 2

2You loop over array a and, inside that loop, over array b. What is the cost?

Question 3

3What is the extra space of a recursive DFS on a tree of height h?

Question 4

4Why is ArrayList.add O(1) amortised even though resizing copies the array?

Question 5

5Building a string of n characters with += on a Java String inside a loop costs:

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    State the time and space complexity of: for i from 0 to n - 1, for j from 0 to 9, print(i * j).

  2. Exercise 2medium

    A function sorts n numbers, then for each element does a binary search in the same array. What is the total time? Could a different structure make it faster?

  3. Exercise 3hard

    Give the time and space of f(n) = (n <= 1) ? 1 : f(n / 2) + f(n / 2) + 1 with integer division. Then say what changes if you compute f(n / 2) once and double it.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need Big-Theta and Big-Omega for interviews?
Mostly no. Interviewers say Big-O but usually mean the tight bound for the worst case. Knowing that Big-O is technically an upper bound helps if someone asks.
Is O(n) always faster than O(n squared)?
For large inputs, yes. For tiny inputs a simple O(n squared) loop can win because of small constants, which is why sorting libraries use insertion sort for very short arrays.
Should I count the output array in space complexity?
Usually not. Say "O(1) extra space, not counting the output" so the interviewer knows you thought about it.

Go deeper

ShareXLinkedInWhatsApp