Fibonacci with O(1) Space

easyPython

Lesson

Space Complexity and Iterative Solutions

When solving problems algorithmically, we often need to balance time complexity (how long the algorithm takes) with space complexity (how much memory it uses). Space complexity measures how much additional memory an algorithm needs as the input size grows.

Many problems have multiple solutions with different space-time tradeoffs. Consider calculating the sum of numbers from 1 to n. A naive approach might store all numbers in an array first, then sum them - this uses O(n) space. But we can solve it more efficiently by keeping a running total as we iterate, using only O(1) space (constant space that doesn't grow with input size).

The key insight for O(1) space solutions is to identify what information you actually need to keep track of at each step. Often, you don't need to remember the entire history of calculations - just the most recent values that affect the next computation.

For iterative problems like sequences, this usually means keeping track of just the previous few values rather than storing the entire sequence. You can "slide" these tracking variables forward as you compute each new value, maintaining constant memory usage regardless of how large n becomes.

This approach is particularly valuable when dealing with large inputs where memory usage matters, or in embedded systems with strict memory constraints.

Example
1def sum_to_n_efficient(n): 2 """Calculate sum of 1 to n using O(1) space""" 3 total = 0 4 for i in range(1, n + 1): 5 total += i 6 return total 7 8# Compare with O(n) space approach: 9def sum_to_n_inefficient(n): 10 """Calculate sum of 1 to n using O(n) space""" 11 numbers = list(range(1, n + 1)) # Stores all numbers 12 return sum(numbers)
L3Only one variable needed - space doesn't grow with n
L4We iterate and update our single tracking variable
L9This approach stores all n numbers in memory first

Key Takeaways

  • •O(1) space means memory usage stays constant regardless of input size
  • •Identify the minimum information needed at each step - often just the last few values
  • •Iterative solutions can often achieve better space complexity than storing entire sequences
Loading...