← DSA roadmap

Topic 1 of 21 · Beginner

Time & Space Complexity

Big-O notation: how to measure how fast code grows as input grows.

Concept

Big-O describes how the running time or memory of an algorithm grows as the input size n grows. We drop constants and keep the fastest-growing term: 3n² + 5n + 2 becomes O(n²).

Common classes from fastest to slowest: O(1) constant, O(log n) logarithmic, O(n) linear, O(n log n), O(n²) quadratic, O(2ⁿ) exponential.

Space complexity counts extra memory used, including recursion stack frames.

Complexity

OperationTimeSpace
Access array indexO(1)—
Binary searchO(log n)—
Single loop over nO(n)—
Merge sortO(n log n)—
Nested loops over nO(n²)—

Code (Python)

def has_pair_with_sum(nums, target):
    # O(n) time, O(n) space using a set
    seen = set()
    for x in nums:
        if target - x in seen:
            return True
        seen.add(x)
    return False

# Brute force would be O(n^2):
# for i in range(n): for j in range(i+1, n): ...

Remember

  • Count loops: nested loops usually multiply.
  • Halving the input each step gives log n.
  • Trade space for time with hash sets / maps.

Practice these interview problems

  • Two Sum
  • Find duplicates in array
  • Analyse complexity of given code
Practice with the AI mentor

Lesson test

Take an 8-question test on “Time & Space Complexity” — concepts, output prediction, bug spotting and interview questions.