01 / 20

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.

Java Computer Science

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.

\( O(1) \)
Constant: same speed regardless of input size
\( O(n) \)
Linear: time grows proportionally with input
\( O(n^2) \)
Quadratic: time explodes with larger inputs

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.

\( O(1) \) Space
Only a few variables: no extra structures needed
\( O(n) \) Space
Creates an extra array or HashMap proportional to input

The Core Tradeoff Visualized

Memory Used (Space) Execution Time Slow + Tiny Fast + Large Sweet Spot Low High Fast Slow

The Fundamental Principle

1
Pre-compute and store results in memory to avoid recalculating them: trading space for time.
2
Recompute values on the fly instead of storing them: trading time for space.
3
Use auxiliary data structures (HashMap, Set, array) to enable faster lookups at the cost of memory.

Classic Pattern: Lookup Table

Brute Force Check every pair of items
Time: \( O(n^2) \)
Space: \( O(1) \)
for each element: check if match vs HashMap Lookup Store items, then look up
Time: \( O(n) \)
Space: \( O(n) \)
map.put(key, val)
map.get(key) → \( O(1) \)

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

1
Identify the bottleneck: Is your code too slow or using too much memory?
2
Analyze current complexity: Write the Big-O for both time and space of your current solution.
3
Ask: can I trade one for the other? If time is the issue, consider adding a data structure. If space is the issue, remove caching.
4
Implement and re-analyze: Verify the new complexity is actually better for the resource you care about.
5
State the tradeoff clearly: "This uses \( O(n) \) extra space but reduces time from \( O(n^2) \) to \( O(n) \)."

Example 1: Finding Duplicates

Problem: Given an array of integers, determine if any value appears at least twice.

// Approach A: Brute Force (save space, slow) for (int i = 0; i < arr.length; i++) for (int j = i + 1; j < arr.length; j++) if (arr[i] == arr[j]) return true; // Time: O(n²) | Space: O(1)
// Approach B: HashSet (use space, fast) Set<Integer> seen = new HashSet<>(); for (int x : arr) { if (seen.contains(x)) return true; seen.add(x); } // Time: O(n) | Space: O(n)

Example 2: Two Sum

Problem: Given an array and a target, find two numbers that add up to the target. Return their indices.

Nested Loops
Check every pair. Time: \( O(n^2) \), Space: \( O(1) \)
HashMap
Store complements. Time: \( O(n) \), Space: \( O(n) \)
// HashMap approach Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) return new int[]{map.get(complement), i}; map.put(nums[i], i); } // Time: O(n) | Space: O(n)

Example 3: Fibonacci Three Ways

Recursive
Time: \( O(2^n) \)
Space: \( O(n) \) stack
Recomputes everything
Memoized
Time: \( O(n) \)
Space: \( O(n) \) cache
Stores computed values
Iterative
Time: \( O(n) \)
Space: \( O(1) \)
Only two variables
Recursive Most Time High Space Memoized Fast More Space Iterative Fast Least Space

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.

int[] memo = new int[n + 1]; Arrays.fill(memo, -1); int fib(int n) { if (n <= 1) return n; if (memo[n] != -1) return memo[n]; // cached! memo[n] = fib(n - 1) + fib(n - 2); return memo[n]; } // Time: O(n) | Space: O(n) for the memo array

Real-World Tradeoff Examples

Database Index
Extra disk space to store the index, but queries run in \( O(\log n) \) instead of \( O(n) \)
Web Cache
Store page content in memory (RAM) to avoid regenerating it on every request
Compression
Trade CPU time to compress data, saving storage space and network bandwidth

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

✕ Ignoring Space Cost
Adding a HashMap "for speed" without realizing it doubles memory usage. Always state the space cost.
✕ Premature Optimization
Choosing a complex \( O(n \log n) \) solution when \( n < 100 \). For \( n < 100 \), brute force is often fine.
✕ One-Sided Analysis
Reporting only time complexity and forgetting to mention space. Both matter for a complete analysis.

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?