🎯 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?” | Time | Space |
|---|---|---|
| Compare every pair | O(n²) | O(1) |
| Sort first, compare neighbours | O(n log n) | O(1)–O(n) |
| Remember seen items in a set | O(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.