Contents

Big O Interview Questions: How to Analyze and Explain Time and Space Complexity | OfferBull

Big O Interview Questions: How to Analyze and Explain Time and Space Complexity

You’ve just written a solution that works on the sample. The interviewer nods, then asks, “What’s the time complexity?” You glance at the loop and say “O(n).” They wait. That pause is the real question. They want the walk, not the slogan.

That’s what Big O interview questions are actually testing. Not whether you can recite a chart. Whether you can look at your own code, name what n is, count the work, and say it so another engineer can follow. Getting the class right matters. Getting it out of your mouth, with space and one assumption, matters more.

This is a practice page for that part of a coding interview: the classes you’ll actually say out loud, twelve “what’s the complexity of this?” questions with spoken answers, and a short script for talking through a messy function. For the wider habit of narrating while you code, use the guide on how to communicate your thought process. If you’re still picking a practice list, Blind 75 vs NeetCode 150 is the next decision.

The examples below are illustrative. I won’t invent a cutoff like “you must say O(n log n) or you fail.”

The classes you’ll actually say out loud

Almost every coding-interview solution lands in a small set of classes. Learn those well enough that you can point to the line that causes each one.

O(1), constant. A handful of operations that do not grow with the input: reading a[i], swapping two variables, checking a field. Hash map lookup is average-case O(1). That “average” is where people get sloppy.

O(log n), logarithmic. The work shrinks by a fraction each step, usually by half. Binary search on a sorted array. Walking down a balanced binary tree. A loop that does n //= 2 until it hits 1.

O(n), linear. You touch each of n items a constant number of times. A single pass. Two passes in a row are still O(n). That second sentence surprises people who count loops instead of work.

O(n log n). A linear number of logarithmic steps, or a logarithmic number of linear steps. This is the usual cost of an efficient comparison sort, and of “for each item, binary search in a sorted structure.” It is also the lower bound for comparison-based sorting, which comes up in sorting and searching interview questions when someone asks if you can go faster. Sometimes yes, if the input has extra structure, like bounded integers.

O(n²), quadratic. Nested work over the same input: a loop inside a loop, both tied to n. Or a triangle of iterations that still grows like n²/2. If n is an array length, notice this early and, if you can, improve it.

O(2^n) and O(n!). You need to recognize these even if they are rarely your final answer. A recursion that branches two ways on n, like naive Fibonacci, is exponential. Generating every permutation is factorial. If you hear yourself say “I recurse on n-1 and n-2,” name the cost before you keep typing.

Space gets the same treatment, in a separate sentence. Extra arrays, hash maps, and the call stack all count. The input itself usually does not, unless they ask for total space. When in doubt, say “O(1) extra space, not counting the input,” or “O(n) extra for the hash set.

/images/posts/big-o-notation-interview-questions/talk-through-bigo.svg A talking order, not a formula to recite. Say the assumption (worst case, unless they ask otherwise), then space.

Twelve “what’s the complexity of this?” questions

These are the kind of snippets an interviewer writes on the board. The spoken answers are illustrative.

1. A single loop

def total(nums):
    s = 0
    for x in nums:
        s += x
    return s

“n is the length of nums. The loop runs once per element and does constant work, so time is O(n). Extra space is O(1).”

2. Two loops, one after the other

def two_passes(nums):
    s = sum(nums)
    m = nums[0]
    for x in nums:
        if x > m:
            m = x
    return s, m

“There are two loops, but they are not nested. Each is O(n), so together that’s O(n), not O(2n) as a final answer. We drop the constant. Extra space is still O(1).”

3. Nested loops over the same range

def all_pairs(nums):
    count = 0
    for i in range(len(nums)):
        for j in range(len(nums)):
            if nums[i] > nums[j]:
                count += 1
    return count

“Outer loop is n, inner loop is n, the body is constant, so time is O(n²). Extra space is O(1).”

4. A triangle, not a full square

def lower_pairs(nums):
    count = 0
    for i in range(len(nums)):
        for j in range(i):
            if nums[j] > nums[i]:
                count += 1
    return count

“The inner loop runs 0, then 1, then 2, up to n-1 times. That’s n(n-1)/2 iterations, which is still O(n²). I would not call this O(n) just because the inner range is smaller than n.”

5. A loop that halves

def steps_until_one(n):
    steps = 0
    while n > 1:
        n //= 2
        steps += 1
    return steps

“n is cut in half each time, so this is O(log n) time and O(1) space. Same shape as binary search, even though there is no array here.”

6. Binary search inside a loop

def each_item_in_sorted(needles, haystack):
    found = 0
    for x in needles:
        if binary_search(haystack, x):
            found += 1
    return found

“Let n be the length of needles and m the length of haystack. For each of the n needles I do O(log m) work, so time is O(n log m). If both arrays are length n, I’d just say O(n log n).”

7. Sort, then a single pass

def has_duplicate_after_sort(nums):
    nums = sorted(nums)
    for i in range(1, len(nums)):
        if nums[i] == nums[i - 1]:
            return True
    return False

“Sorting dominates, so time is O(n log n). sorted() usually takes O(n) extra space. If I only needed to detect a duplicate, a hash set is average O(n) time and O(n) space, and I wouldn’t sort.”

8. A hash set in a loop

def has_duplicate(nums):
    seen = set()
    for x in nums:
        if x in seen:
            return True
        seen.add(x)
    return False

“Average time is O(n), because each lookup and insert is average O(1), and we do n of them. Extra space is O(n) for the set. If you want worst-case time, a pathological hash can degrade to O(n²). I quote the average unless you ask for the worst case, and I’ll say that out loud.”

9. Walking a tree

def subtree_sum(node):
    if node is None:
        return 0
    return node.val + subtree_sum(node.left) + subtree_sum(node.right)

“If n is the number of nodes, we visit each once, so time is O(n). Extra space is the call stack, which is O(h), the height: O(log n) if balanced, O(n) if skewed. I wouldn’t say O(1) space just because I didn’t allocate an array.”

10. Naive recursive Fibonacci

def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)

“Each call branches into two more, and the depth is n, so time is O(2^n). Extra space is O(n) for the call stack, not exponential, because the branches share the stack as they return. I’d offer the fix next: memoization or an iterative pass, which brings time down to O(n).”

11. Building every subset

def all_subsets(nums):
    out = []
    def go(i, path):
        if i == len(nums):
            out.append(path[:])
            return
        go(i + 1, path + [nums[i]])
        go(i + 1, path)
    go(0, [])
    return out

“There are 2^n subsets, and copying a path costs up to O(n), so time is O(n · 2^n). Extra space is O(n) for the recursion and the current path, plus the output if we’re counting it. I’d ask whether they want the output included.”

Permutations are the sibling question: n! of them, O(n) to write each, so O(n · n!).

12. Appending versus building a string the slow way

def join_slow(parts):
    s = ""
    for p in parts:
        s = s + p
    return s

def join_ok(parts):
    out = []
    for p in parts:
        out.append(p)
    return "".join(out)

“If each p is a single character and there are n of them, the slow version copies a longer string on every step: 1 + 2 + … + n, which is O(n²). The list version appends in amortized O(1), then joins once, so it’s O(n). The loop looks linear and isn’t, because each iteration’s work grows.”

Amortized is a word you should only use if you can finish the sentence. For a dynamic array: “Sometimes append copies the whole buffer, but the copies are rare enough that n appends are still O(n) total.”

/images/posts/big-o-notation-interview-questions/whiteboard-complexity.jpg Practice this gesture: point at the loop that dominates, then say the class. The boxes are blank on purpose; the habit is the point.

How to say it out loud

Your code is already on the board, it’s a little messy, and the interviewer asks in the middle of a thought. Use a fixed order so you don’t skip space.

Name n: “n is the number of meetings,” or “n is the length of the string, m is the size of the dictionary.” Walk the dominant work while pointing at the code. Drop constants and lower-order terms, and say that’s what you’re doing. State the case: worst case, unless they asked for average. If a hash map is involved, add that caveat in one sentence. Give extra space, including the stack. Then, if there’s an obvious improvement, offer it once.

A slightly messy function, said the way I’d say it in the room (illustrative):

def score(items, lookup, text):
    total = 0
    for item in items:
        if item in lookup:
            for ch in text:
                total += 1
    return total

“n is the length of items, m is the length of text. lookup is a set. For each of the n items I do an average O(1) membership check, and on a hit I scan all of text. Worst case every item hits, so time is O(n · m), not O(n). Extra space is O(1) beyond the inputs. If lookup were a list, that check would be O(k) and the whole thing would get worse.”

If you realize mid-sentence that you were wrong, correct it. “Wait, I treated the inner scan as constant. It isn’t. Let me redo that. It’s O(n · m).” Interviewers would rather hear the correction than a confident O(n) that doesn’t match the board.

/images/posts/big-o-notation-interview-questions/speak-aloud.jpg The skill is spoken, not just written. Close the editor and say the paragraph once, with a timer if you tend to ramble.

The coding interview patterns post helps here too: once you know you’re in a sliding window or a heap, the complexity is usually attached to the pattern. Still walk the code.

The mistakes that make a right-looking answer sound shaky

The most common one is counting loops. Two separate loops become “O(2n)” said as if it were a different class, or a triangle nest becomes “less than O(n²)” as if the half changed the class. Count the work. Then drop the constants.

The next one is treating a hash map as a free O(1) coupon. Building the map is O(n). Looking up n times is average O(n) in total, and O(n) space. If you only say “it’s O(1) because I used a dict,” you’ve described a line, not the function.

Space gets skipped, or the stack gets skipped. Recursion is not free. A DFS on a linked-list-shaped tree is O(n) space whether you meant it or not.

People also import folklore. I won’t repeat passing scores or “they fail you if it isn’t n log n.” Some problems have a linear solution. Some don’t. Talk about this input and this function.

And don’t bluff the difference between average and worst case. Quicksort is the usual example: average O(n log n), worst O(n²). It’s fine to say “I know it can go quadratic if the pivot is terrible, so I’d use the library sort or mention the risk.” Better than inventing a proof.

Practice the talking, not just the chart

Knowing the chart is cheap. The hard part is doing this on code you just improvised, while someone watches. Take a problem from your list, write a solution, then close the editor and say, in under a minute: what n is, the time, the space, the case, and one thing you’d change. Pair it with the thought-process guide.

OfferBull is an AI mock interview app for iOS and Android. A voice interviewer asks questions aloud. You answer by speaking. Paste a job description or upload a resume for tailored questions. Follow-ups based on what you said and what’s on the resume. While you practice, you get answer suggestions and STAR structures. English and Chinese. Use it before a real coding interview, not during one.

Start an AI mock interview

FAQ

Do I need the formal definition of Big O in a coding interview? Usually no. You should be able to say that O(n) means the work grows at most linearly with n, for large enough n, and that you drop constants. A formal proof is rarely the point of a coding round. If the role is more theoretical and they ask, then give the definition. Don’t lead with it.

When should I quote average case versus worst case? Default to worst case, then make exceptions out loud. Hash maps: quote average, mention the worst. Quicksort: quote average, mention the worst, and say how you’d avoid it.

Do I always have to state space complexity? I’d get into the habit, even when they only asked for time. It takes one sentence, and it catches the hash map or the recursion you were about to forget. If they wave it off, stop.

What if I get the class wrong and notice later? Correct it as soon as you see it, and walk the new count. “I missed the inner scan. It’s O(n · m), not O(n).” Changing your mind with evidence looks like engineering.


Practice This Out Loud

Tonight: pick one solution you already wrote this week, preferably one with a nested loop or a hash map. Don’t look at notes. In sixty seconds, say what n is, the time, the extra space, and one improvement. Then open the editor and check whether the words matched the code. If you want a voice interviewer to interrupt you and ask “why not O(n)?”, practice that in a mock, then close the app before any real interview. → Practice Now


Take Control of Your Career Path: