Introduction

Complexity Analysis

Explain the work your code performs, including collection operations, repeated copying, amortized costs, and phase-specific constraints.

Free~12 min

What is complexity analysis?

Complexity analysis explains how work and storage grow with input size. Define the quantity first: n might mean the number of intervals, the number of nodes, or the number of timestamps stored for one key. A useful answer names both the input and the operation: "lookup takes O(log n), where n is this key's history length."

We count operations under an explicit model. Bounded integer arithmetic and comparisons are usually treated as constant-time in interview problems. String comparison, hashing a long key, copying a collection, and calling a helper may require more work. The implementation and problem constraints decide which costs apply.

Correctness and efficiency need separate arguments. A passing example shows one observed result. A complexity argument explains how much work remains possible as inputs grow.

Core operations

Key patterns

Count the work

Count how often the operation inside a loop can execute over the entire run.

When to use - nested loops, repeated helpers, or code that looks short but scans a growing collection.

How it works - sequential work adds; independent repeated work multiplies. When two pointers only move forward, count their total movement instead. Reading a helper's body prevents a hidden scan from being treated as constant-time.

Example: Count all cross-list matches. Comparing [2, 8, 2] with [2, 5] performs six comparisons and finds two matches. In general, lengths n and m produce n * m comparisons, including when few values match.

Note
Keep independent sizes separate - write O(nm) until the contract establishes a relationship between the two lengths.

Operation costs

Expand collection operations into the elements they must inspect, move, or allocate.

When to use - a loop copies prefixes, enumerates keys, sorts repeatedly, or removes items from the front of an array.

How it works - summing copied prefix lengths gives 1 + 2 + ... + n, which is quadratic. Appending each value to one growing result avoids copying the whole prefix on each iteration under a dynamic-array model.

Sorting also needs an explicit cost model. Under an O(n log n) comparison-sort model with constant-cost comparisons, sorting followed by one linear scan costs O(n log n) overall. Comparing long strings can add work per comparison. Python's sorted(values) and JavaScript/TypeScript's [...values].sort((a, b) => a - b) first allocate a separate result; sorting the existing list or array mutates it, and the sorting algorithm can still need temporary storage. ECMAScript does not require a particular sorting algorithm or time/space bound, so state this model when explaining a JavaScript or TypeScript solution.

Example: Copy filtered values. Reading [7, -2, 4] visits three values and appends two. For n values, this takes O(n) total work under amortized append and uses O(n) output storage in the worst case.

Note
Account for the operation before its result - reading the length of a newly enumerated key array is cheap, but creating that array still visits the keys.

Per-operation and total cost

Charge each item for the work it can cause across a sequence of operations.

When to use - cleanup queues, monotonic stacks, or a loop that sometimes removes many earlier items.

How it works - if each index enters a stack once and leaves once, total pushes and pops are O(n). A single iteration may still perform O(n) pops. This is an amortized argument, without an assumption about randomly distributed inputs.

Example: Keep increasing candidates. For [5, 9, 3], push 5 and 9; processing 3 pops both and then pushes 3. Three pushes and two pops occurred even though the last iteration did most of the removal work.

Note
Count revisits too - a cleanup routine that removes each expired item once can still be expensive if every call also scans all surviving items.

Space and phase constraints

Separate required output from temporary storage, and apply only the constraints of the selected task phase.

When to use - recursive solutions, sorted histories, or challenges that introduce stronger requirements in later levels.

How it works - count simultaneously live storage. A recursion stack depends on active depth, while retaining a copy of every prefix can use quadratic storage. If timestamps arrive in increasing order, inserting at the end does not move existing timestamps; an arbitrary-insertion bound would describe a different contract.

Example: Find a timestamp boundary. In [3, 8, 12], a query of 9 checks the middle value 8, then 12, leaving index 1 as the last eligible position. The search uses O(log n) comparisons and O(1) auxiliary space for this one key's n sorted timestamps. Apply this reasoning in Time-based KV Level 1.

Note
State the scope of the bound - a logarithmic lookup does not make every operation on the store logarithmic; analyze writes, cleanup and output construction separately.

When to reach for complexity analysis

  • The input limits make a repeated scan potentially too expensive.
  • A solution passes examples but the task asks for an efficiency guarantee.
  • A helper inside a loop allocates or enumerates a collection.
  • One operation occasionally processes many previously stored items.
  • A later challenge phase changes the required cost or allowed input order.
  • Recursive code uses stack space that is absent from an explicit collection count.

Done reading? Mark it so it sticks in your dashboard.

Discussion