LESSON 03 / 04

Space Complexity

Memory matters too. Learn to measure the extra space an algorithm needs — and the classic time-vs-space trade-off.

🎓Easylevel
⏱️25 minto finish
✏️2activities

📂 Big O & Problem Solving🏷️ Big O

🎯 By the end of this lesson you can…

  • Measure extra memory with Big O
  • Compare in-place and copying solutions
  • Explain the time–space trade-off
⚡ JavaScript space.js 👆 Tap a line to explain it
1function reverseCopy(arr) {2  const out = [];3  for (let i = arr.length - 1; i >= 0; i--) out.push(arr[i]);4  return out;5}6function reverseInPlace(arr) {7  let l = 0;8  let r = arr.length - 1;9  while (l < r) {10    [arr[l], arr[r]] = [arr[r], arr[l]];11    l++;12    r--;13  }14  return arr;15}16console.log(reverseCopy([1, 2, 3]), reverseInPlace([1, 2, 3]));
Approach to “has duplicates?”TimeSpace
Compare every pairO(n²)O(1)
Sort first, compare neighboursO(n log n)O(1)–O(n)
Remember seen items in a setO(n)O(n)
💡 Concept check
A recursive function calls itself n levels deep. What extra space does the call stack use?
🛠️ Duplicates, fast

Write hasDuplicate(nums) in O(n) time using a set. Return true/false.

📌 Key takeaways

  • Space complexity counts extra memory, not the input itself.
  • A few variables → O(1). A new array the size of the input → O(n).
  • We often spend memory (a hash set) to save time.

Finished reading & practising?

Saved in this browser. Create a free account to keep it forever.