Skip to lesson

Stating Time and Space Complexity

Every coding answer ends with "what is the time and space complexity?", and a number alone does not earn full marks. The interviewer is checking that you can give both, with the reason, and that you notice the loop hiding inside a library call.

Quick rules for loops, recursion and collection calls

Big-O describes how the work of an algorithm grows as the input size n grows, keeping only the fastest-growing term and ignoring constants.

Complexity can be read straight off the code. Example 1 counts the steps of five common loop shapes for n = 1,024, so each rule shows up in real numbers.

Example 1 · Counting steps for common loop shapes

LoopShapesDemo.javaJava
public class LoopShapesDemo {    static long nested(int n) {        long steps = 0;        for (int i = 0; i < n; i++)            for (int j = 0; j < n; j++) steps++;        return steps;    }
    static long triangle(int n) {        long steps = 0;        for (int i = 0; i < n; i++)            for (int j = i + 1; j < n; j++) steps++;        return steps;    }
    static long sequential(int n) {        long steps = 0;        for (int i = 0; i < n; i++) steps++;        for (int i = 0; i < n; i++) steps++;        return steps;    }
    static long halving(int n) {        long steps = 0;        for (int i = n; i > 1; i /= 2) steps++;        return steps;    }
    static long nTimesLog(int n) {        long steps = 0;        for (int i = 0; i < n; i++)            for (int j = 1; j < n; j *= 2) steps++;        return steps;    }
    public static void main(String[] args) {        int n = 1024;        System.out.println("nested      O(n^2)     " + nested(n));        System.out.println("triangle    O(n^2)     " + triangle(n));        System.out.println("n log n     O(n log n) " + nTimesLog(n));        System.out.println("sequential  O(n)       " + sequential(n));        System.out.println("halving     O(log n)   " + halving(n));    }}
Output
nested      O(n^2)     1048576
triangle    O(n^2)     523776
n log n     O(n log n) 10240
sequential  O(n)       2048
halving     O(log n)   10

What this code does

  • The triangle loop does about half the work of the full nested loop, n(n - 1)/2, but it is still O(n²): constants are dropped.
  • Two loops in a row add (2n is O(n)); a loop that halves runs log₂ 1024 = 10 times; a halving loop inside an n loop gives n log n.

Loops one after another add, nested loops multiply, and a loop that halves or doubles its variable runs about log₂ n times. For recursion, multiply the work per call by the number of calls: merge sort splits in two halves with O(n) work, so O(n log n); naive Fibonacci calls itself twice on n - 1, so O(2ⁿ). Revise: Counting loops (opens in a new tab) and logarithmic loops (opens in a new tab)

Library calls have costs too, and you must add them:

  • ArrayList.get O(1); contains, indexOf and remove(0) O(n); add at the end O(1) on average.
  • HashMap and HashSet get, put, contains: O(1) average. TreeMap and TreeSet: O(log n).
  • Arrays.sort and Collections.sort: O(n log n). PriorityQueue offer and poll: O(log n), peek O(1).
  • String.length and charAt O(1); substring, equals, toCharArray, split, indexOf: O(length).

Predict the output

Count the steps

Work out how many times the counter goes up. The count shows the complexity.

Round 1 of 2

A loop that doubles. What does it print?

int count = 0;
for (int i = 1; i < 16; i *= 2) {
count++;
}
System.out.println(count);

Hidden costs: substring, contains on a list, concatenation in loops

A hidden cost is a library call that is a loop inside, such as list.contains, substring or String +=, so it makes the loop around it more expensive.

A single line can hide a whole loop. Example 2 times String += against StringBuilder, and list.contains against set.contains, on 20,000 items.

Example 2 · Hidden costs measured

HiddenCostDemo.javaJava
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;
public class HiddenCostDemo {    public static void main(String[] args) {        int n = 20_000;
        long t0 = System.nanoTime();        String s = "";        for (int i = 0; i < n; i++) {            s += "x";                       // copies the whole string each time: O(n²)        }        long t1 = System.nanoTime();        StringBuilder sb = new StringBuilder();        for (int i = 0; i < n; i++) {            sb.append('x');        }        long t2 = System.nanoTime();        System.out.println("String +=      " + (t1 - t0) / 1_000_000 + " ms, length " + s.length());        System.out.println("StringBuilder  " + (t2 - t1) / 1_000_000 + " ms, length " + sb.length());
        List<Integer> list = new ArrayList<>();        Set<Integer> set = new HashSet<>();        for (int i = 0; i < n; i++) {            list.add(i);            set.add(i);        }        long t3 = System.nanoTime();        int foundInList = 0;        for (int i = 0; i < n; i++) if (list.contains(n - 1 - i)) foundInList++;   // O(n) each        long t4 = System.nanoTime();        int foundInSet = 0;        for (int i = 0; i < n; i++) if (set.contains(n - 1 - i)) foundInSet++;        long t5 = System.nanoTime();        System.out.println("list.contains  " + (t4 - t3) / 1_000_000 + " ms, found " + foundInList);        System.out.println("set.contains   " + (t5 - t4) / 1_000_000 + " ms, found " + foundInSet);    }}
Sample output
String +=      103 ms, length 20000
StringBuilder  2 ms, length 20000
list.contains  388 ms, found 20000
set.contains   1 ms, found 20000

What this code does

  • Both loops look like O(n), but s += "x" copies about n²/2 characters in total and list.contains scans up to n elements per call.
  • The fixes keep the same answers: StringBuilder for building text and a HashSet for membership.

list.contains(x) inside a loop scans the list each time, so the loop is O(n²), not O(n). s.substring(i, j) copies j - i characters, so building every substring is O(n³) overall. result += piece on a String copies the whole string each time: O(n²) characters for n appends.

The fixes are standard: a HashSet for membership, indexes or a StringBuilder instead of many substrings, and StringBuilder.append (amortized O(1)) for building text. Say the hidden cost aloud before the interviewer does.

Find the bug

Find the hidden loop

Each method claims to be O(n). Click the line whose hidden cost makes it slower.

Does the list contain a duplicate?

Round 1 of 2
The timings in the example are a sample and will differ on your computer, but the gap between the slow and fast versions grows quickly with n.

Space: auxiliary vs output, and the recursion stack

Auxiliary space is the extra memory an algorithm uses besides the input; output space is the memory for the answer itself, and is often not counted.

Space is the memory beyond the input. Example 3 records how deep a recursive sum and a recursive binary search go, then overflows the stack on purpose.

Example 3 · Recursion depth is the space cost

RecursionSpaceDemo.javaJava
public class RecursionSpaceDemo {    static int maxDepth;
    static long sum(int[] a, int i, int depth) {        maxDepth = Math.max(maxDepth, depth);        if (i == a.length) return 0;        return a[i] + sum(a, i + 1, depth + 1);          // depth grows to n    }
    static int search(int[] a, int key, int lo, int hi, int depth) {        maxDepth = Math.max(maxDepth, depth);        if (lo > hi) return -1;        int mid = lo + (hi - lo) / 2;        if (a[mid] == key) return mid;        return a[mid] < key ? search(a, key, mid + 1, hi, depth + 1)                            : search(a, key, lo, mid - 1, depth + 1);   // depth about log n    }
    public static void main(String[] args) {        int[] a = new int[1024];        for (int i = 0; i < a.length; i++) a[i] = i;
        maxDepth = 0;        System.out.println("sum = " + sum(a, 0, 1) + ", max depth " + maxDepth);        maxDepth = 0;        System.out.println("search(1023) = " + search(a, 1023, 0, a.length - 1, 1) + ", max depth " + maxDepth);
        try {            sum(new int[1_000_000], 0, 1);        } catch (StackOverflowError e) {            System.out.println("sum over 1,000,000 values: StackOverflowError");        }    }}
Output
sum = 523776, max depth 1025
search(1023) = 1023, max depth 11
sum over 1,000,000 values: StackOverflowError

What this code does

  • Recursive sum keeps n + 1 frames on the stack at its deepest, so it uses O(n) space even though it has no array or list of its own.
  • Binary search halves the range each call, so depth is about log₂ n + 1. A million-deep recursion overflows Java's default stack, which is why a loop is safer for linear recursion.

Interviewers usually mean auxiliary space, so say which you are counting: "O(1) extra space, not counting the output list". Recursion uses stack memory: each active call keeps a stack frame, so space is the maximum depth, not the number of calls.

Recursive sum of n numbers is O(n) space; recursive binary search is O(log n); naive Fibonacci makes O(2ⁿ) calls but only O(n) depth. Around a million nested plain calls usually throws StackOverflowError, which is why deep recursion is rewritten as a loop.

How to phrase it in the interview

The dominant term is the fastest-growing part of a cost, so O(n² + n) is O(n²) and O(n log n + n) is O(n log n).

Give time and space in one sentence each, with the reason. Example 4 solves a top-k words problem and carries its own complexity sentence in the comments.

Example 4 · A full solution with its complexity sentence

TopKWordsDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class TopKWordsDemo {    // Time: O(n) to count + O(m log m) to sort the m distinct words -> O(n + m log m).    // Space: O(m) extra for the map and the entry list (output of size k not counted).    static List<String> topK(String[] words, int k) {        Map<String, Integer> count = new HashMap<>();        for (String w : words) {            count.merge(w, 1, Integer::sum);        }        List<Map.Entry<String, Integer>> entries = new ArrayList<>(count.entrySet());        entries.sort((a, b) -> a.getValue().equals(b.getValue())                ? a.getKey().compareTo(b.getKey())                : Integer.compare(b.getValue(), a.getValue()));        List<String> result = new ArrayList<>();        for (int i = 0; i < k && i < entries.size(); i++) {            result.add(entries.get(i).getKey() + "=" + entries.get(i).getValue());        }        return result;    }
    public static void main(String[] args) {        String[] words = {"upi", "card", "upi", "cash", "card", "upi", "wallet"};        System.out.println(topK(words, 2));    }}
Output
[upi=3, card=2]

What this code does

  • Say it in one breath: "O(n + m log m) time, n words and m distinct words, because of the counting pass and the sort; O(m) extra space for the map."
  • If asked to improve, a heap of size k gives O(n + m log k), which matters when k is much smaller than m.

Build the sentence in four moves:

  • Name each part: "sorting is O(n log n), the loop is O(n), each map lookup is O(1) on average".
  • Combine and keep the dominant term: "so O(n log n) time overall".
  • Space: say auxiliary versus output, and include the recursion depth.
  • Add a caveat if needed: average versus worst case, or which variable is which.

Name every variable when there are several: "O(n · k) where n is the number of words and k the longest word". Say amortized for things like ArrayList.add, and if you are unsure, reason aloud from the loops instead of guessing a famous answer.

Order of execution

Say it in four moves

Put the parts of a strong complexity answer in order.

Next step

Check your understanding

12 quick questions