Work out how the runtime grows as the input grows, then drop constants and lower order terms. Read the code structure: sequential blocks add, nested loops multiply, and recursive calls follow the recurrence. Space is the extra memory you allocate beyond the input, including the call stack. State the worst case by default, and call out the average case separately if they differ meaningfully.
Why interviewers ask this
Complexity analysis is the shared vocabulary for talking about performance, so the interviewer wants to know you can reason about scale before you write code rather than after profiling in production. They are checking that you separate the growth rate from micro optimizations, that you remember space as well as time, and that you can spot the hidden cost in things like sorting inside a loop or copying a list on every iteration.
How to structure your answer
- Name the input and say what n actually measures.
- Walk the code top down, adding sequential work and multiplying nested work.
- State time and space separately, dropping constants.
- Flag the worst case and the input that triggers it.
Example answer
I start by naming n, because half the confusion in these conversations comes from two people measuring different things. Then I read the code structurally. Sequential blocks add, so the biggest one wins; nested loops multiply; a recursive call becomes a recurrence I can either expand or recognize. For space I count anything I allocate beyond the input, and I always include the call stack, which is the bit people forget with recursion. A concrete example: I had a function that looked linear because it was one loop over a list of orders, but inside it we called a helper that looked a record up by id in a list. That lookup was linear, so the real cost was quadratic, and it only showed up once one customer hit about forty thousand orders. We swapped the list for a dictionary keyed by id and the endpoint went from around nine seconds to under two hundred milliseconds. So my rule is to look inside every call, not just the loops I can see.
Walking into this interview soon? GhostPilot listens to your live call, spots the question the moment it is asked, and puts a structured answer on your screen in real time. Try it on your next mock, or grab a $29 Session Pass, no subscription, for the real thing.
See how it worksFollow-up questions to expect
- What is the complexity if the input is already sorted?
- How would amortized analysis change your answer for a dynamic array?
- When would you accept a worse big O for a better real world constant?
Related software engineer questions
Your interviewer will ask their own version of this. Paste your actual job description into the free Question Predictor and get the 20 questions that role is most likely to ask, with what each one is really probing.
Predict my questions