01 / 21

Time/Space
Tradeoffs

Every algorithm makes a choice: use more memory to run faster, or use less memory and accept slower execution. Master this fundamental tension in C++.

C++

What Is a Tradeoff?

In computing, a tradeoff is a situation where improving one quality of a program comes at the cost of another. The most common tradeoff is between time (how fast code runs) and space (how much memory it uses).

Time
The number of operations an algorithm performs, measured in time complexity using Big-O notation.
Space
The amount of memory (RAM) an algorithm uses, measured in space complexity using Big-O notation.

The Balancing Act

Time Space Slower Less Memory Use more memory → Run faster Use less memory → Run slower

Why Does This Matter?

In real-world C++ programs, you face finite resources. A game running on a phone has limited RAM. A web server must respond in milliseconds. Understanding tradeoffs lets you choose the right tool for each constraint.

Embedded Systems
Tiny memory budgets: must minimize space even if it costs time.
High-Frequency Trading
Nanoseconds matter: spend all the memory you need for speed.
Balanced Apps
Most apps: find a practical middle ground between both.

The Core Principle

Space Complexity Time Complexity Slow + Compact Fast + Spacious Sweet Spot More → More ↑

Quick Big-O Refresher

Big-O notation describes how an algorithm's resource usage grows as the input size \( n \) increases. We apply it to both time and space.

Notation Growth Example
\( O(1) \) Constant Array index access
\( O(\log n) \) Logarithmic Binary search
\( O(n) \) Linear Single loop
\( O(n^2) \) Quadratic Nested loops

Caching vs Recomputing

The most common time/space tradeoff pattern: cache results you'll need again, or recompute them each time.

Cache / Memoize
Store previously computed results in a table (hash map, array). Uses more space but avoids redundant work: faster.
Recompute
Calculate the result fresh every time it's needed. Uses less space but repeats work: slower.

Example: Fibonacci

Computing \( F(n) \), the \( n \)-th Fibonacci number, is the classic illustration of this tradeoff.

Naive Recursion F(5) F(4) F(3) F(3) F(2) F(2) F(1) ... Time: \( O(2^n) \) Space: \( O(n) \) stack Memoized F(5) F(4) F(3) F(2) Cache F(2)=1 F(3)=2 F(4)=3 Time: \( O(n) \) Space: \( O(n) \) cache

Fibonacci in C++ Code

// Naive: O(2^n) time, O(n) space int fib(int n) { if (n <= 1) return n; return fib(n-1) + fib(n-2); }
// Memoized: O(n) time, O(n) space int memo[1001]; int fib(int n) { if (n <= 1) return n; if (memo[n] != 0) return memo[n]; memo[n] = fib(n-1) + fib(n-2); return memo[n]; }

How to Apply the Tradeoff

1
Identify the bottleneck. Is your program too slow (time) or using too much memory (space)?
2
Look for repeated work. Are you computing the same thing more than once? That's a caching opportunity.
3
Consider precomputation. Can you build a lookup table once and query it in \( O(1) \)?
4
Check your constraints. How much memory can you afford? Does the speedup justify it?
5
Implement and measure. Profile before and after: real data beats theory.

Example: Lookup Tables

Problem: Given a character, determine if it is a vowel. You'll check this millions of times in a text-processing loop.

Approach A: Check each time
Use an if-chain: 5 comparisons per call. Time per call: \( O(1) \) but with a large constant. Space: \( O(1) \).
Approach B: Lookup table
Pre-build a bool array[256]. Time per call: \( O(1) \) with a single array access. Space: \( O(1) \) but 256 bytes extra.
// Precomputed lookup table bool isVowel[256] = {false}; isVowel['a'] = isVowel['e'] = isVowel['i'] = isVowel['o'] = isVowel['u'] = true; // Now: one array access instead of 5 comparisons if (isVowel[ch]) { /* ... */ }

Example: Two Sum Problem

Given an array of \( n \) integers and a target, find two numbers that add up to the target.

Approach Time Space
Brute Force (nested loops) \( O(n^2) \) \( O(1) \)
Hash Map lookup \( O(n) \) \( O(n) \)
// Hash map approach: O(n) time, O(n) space unordered_map<int,int> seen; for (int i = 0; i < n; i++) { int comp = target - arr[i]; if (seen.count(comp)) return {seen[comp], i}; seen[arr[i]] = i; }

Example: Finding Duplicates

Given \( n \) numbers, determine if any value appears more than once. Three approaches show the tradeoff spectrum:

Brute Force
Compare every pair. Time: \( O(n^2) \). Space: \( O(1) \).
Sort First
Sort, then scan neighbors. Time: \( O(n \log n) \). Space: \( O(\log n) \) (for `std::sort`).
Hash Set
Insert into set, check on each insert. Time: \( O(n) \). Space: \( O(n) \).

The Tradeoff Spectrum

Slow + Compact Fast + Spacious Brute Force \( O(n^2) / O(1) \) Sort + Scan \( O(n \log n) / O(\log n) \) Hash Set \( O(n) / O(n) \) More memory used →

Common Mistakes

Always choosing speed
Using excessive memory for a tiny speedup. A hash map for 10 elements may be slower than a simple array due to overhead.
Ignoring cache effects
Big-O hides constants. A cache-friendly \( O(n \log n) \) sort can beat a theoretically faster \( O(n) \) hash approach on small data.
Premature optimization
Adding complexity before measuring. Always profile first: the bottleneck may not be where you think.

Summary Table

Pattern Time Space When to Use
Memoization Faster \( +O(n) \) Overlapping subproblems
Lookup Table \( O(1) \) access Table size Repeated queries
Hash Map \( O(1) \) avg \( O(n) \) Fast search/insert
In-place Sort \( O(n \log n) \) \( O(\log n) \) Memory-constrained (avoids \(O(n)\) space)
Recomputation Slower Minimal Tiny memory budget

Question 1 of 5

The naive recursive Fibonacci function has time complexity \( O(2^n) \). By adding an array to store previously computed values, the time complexity drops to:

Question 2 of 5

A programmer replaces a nested loop (\( O(n^2) \) time, \( O(1) \) space) with a hash map approach (\( O(n) \) time, \( O(n) \) space). What tradeoff was made?

Question 3 of 5

You are writing software for an embedded device with only 2 KB of RAM. Which approach to finding duplicates in a list of 400 integers is most appropriate?

Question 4 of 5

A lookup table of size 256 is created to instantly check character properties. The table uses 256 bytes of memory. What is the time complexity of each lookup?

Question 5 of 5

Which statement best describes the time-space tradeoff principle?