Time/Space
Tradeoffs
Every algorithm faces a fundamental choice: use more memory to run faster, or use less memory and accept slower execution. Master this core concept to write smarter Java programs.
What is Time Complexity?
Time complexity measures how the number of operations grows as the input size \( n \) increases. We use Big-O notation to express this growth rate.
What is Space Complexity?
Space complexity measures how much extra memory your algorithm uses as \( n \) grows. This includes arrays, HashMaps, stacks, and any additional data structures you create.
The Core Tradeoff Visualized
The Fundamental Principle
Classic Pattern: Lookup Table
Optimizing for Time vs Space
| Optimize for Time | Optimize for Space | |
|---|---|---|
| Strategy | Cache results, use lookup tables | Compute on the fly, reuse variables |
| Memory | Higher | Lower |
| Speed | Faster | Slower |
| Best When | Speed is critical, memory is cheap | Memory is limited, speed is adequate |
| Java Example | HashMap, memoization | Two pointers, in-place sorting |
How to Apply the Tradeoff
Example 1: Finding Duplicates
Problem: Given an array of integers, determine if any value appears at least twice.
Example 2: Two Sum
Problem: Given an array and a target, find two numbers that add up to the target. Return their indices.
Example 3: Fibonacci Three Ways
Space: \( O(n) \) stack
Recomputes everything
Space: \( O(n) \) cache
Stores computed values
Space: \( O(1) \)
Only two variables
Memoization: Trading Space for Time
Memoization stores the results of expensive function calls so that when the same inputs occur again, the cached result is returned instead of recomputing.
Real-World Tradeoff Examples
Sorting Tradeoffs in Java
| Algorithm | Time | Space | Tradeoff |
|---|---|---|---|
| Bubble Sort | \( O(n^2) \) | \( O(1) \) | Saves space, very slow |
| Merge Sort | \( O(n \log n) \) | \( O(n) \) | Fast, needs extra array |
| Quick Sort | \( O(n \log n) \) | \( O(\log n) \) | Fast, small stack overhead |
| Counting Sort | \( O(n + k) \) | \( O(k) \) | Fastest, needs range array |
Common Mistakes
Question 1 of 5
A student rewrites a method to use a HashMap instead of nested loops. The time goes from \( O(n^2) \) to \( O(n) \). What most likely happened to space complexity?
Question 2 of 5
Which of the following is an example of trading time for space (using more time to save memory)?
Question 3 of 5
A naive recursive Fibonacci function has time complexity \( O(2^n) \). After adding memoization, what is the new time complexity?
Question 4 of 5
Merge Sort uses \( O(n) \) extra space while Quick Sort uses \( O(\log n) \). Both have average time \( O(n \log n) \). When would you prefer Merge Sort despite its higher space cost?
Question 5 of 5
You have an algorithm with \( O(n^2) \) time and \( O(1) \) space. You add a HashSet and reduce time to \( O(n) \) with \( O(n) \) space. For \( n = 1{,}000{,}000 \), which statement is most accurate?