How do you work out and explain the time and space complexity of your solution?
AlgorithmsJunior
In shortName the inputs, find the cost of each step including library calls, multiply nested loops and add sequential steps, keep the dominant term, and state time and space separately with the trade-off you chose.
Model answer
A reliable way to do it, out loud:
- Name the inputs. “n is the number of orders, m is the number of products.” Different inputs get different letters.
- Cost of each step, including library calls:
containson a list is O(n),sortis O(n log n), a hash map lookup is O(1) on average, removing from the front of an array list is O(n). - Combine. Nested loops multiply, steps that follow each other add.
- Simplify. Drop constants and keep the dominant term: O(2n + n log n) is O(n log n).
- Space. Count extra memory: sets, maps, copies, and the recursion depth.
Then say it as one sentence with the trade-off: “This is O(n) time and O(n) space because of the hash set; the sort-based version would be O(n log n) time with less extra memory.”
If the interviewer pushes, distinguish worst case (a hash map degrading with collisions), average case, and amortized cost (dynamic-array appends are O(1) amortized because resizes are rare).
What they're looking for
A systematic method rather than a guess, awareness of hidden costs (contains on a list, sorting, string building), naming separate variables for separate inputs, and stating both time and space. Bonus for mentioning worst vs average vs amortized.
Common mistakes
- Saying "it's O(n)" for code with contains or indexOf inside a loop.
- Calling two different input sizes both "n".
- Forgetting space complexity, or the recursion stack.
More algorithms questions
- What's the difference between a stack and a queue, and when would you use each?Junior
- How do you find the first occurrence of a value in a sorted array that has duplicates?Mid-level
- When would you use BFS instead of DFS, and vice versa?Mid-level
- How do you approach a dynamic programming problem?Mid-level