AlgoTales · Roadmap

Space optimization

Intermediate · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Space optimisation means keeping only the part of your table that the next step still needs, instead of the whole table. If each row depends only on the previous row, two rows are enough. It lets the same answer fit in a tiny fraction of the memory.

Practical use cases

  • Web app: Comparing two huge uploaded files. An admin tool compares two 100,000-line CSV files to show what changed. Storing a table for every pair of lines would need billions of cells and crash the server. Since each row of the table only needs the row before it, the code keeps just two rows and finishes using a few megabytes. The comparison page still highlights every changed line, but the server memory stays flat even when someone uploads a file ten times bigger than usual.
  • Web app: Running balance on a long passbook. A passbook page calculates the cheapest way through months of fees and offers. Each month needs only last month's result, so the code keeps two variables instead of an array of 10,000 entries. The page loads faster, the server handles more visitors at once, and nobody needs to buy a bigger machine just to show a long history of fees.
  • System: Memory-limited devices and streaming. Small devices and live data feeds cannot hold the full history. They keep just the last few values and discard the rest as new data arrives. In each of these, keeping only the last few values rather than the full history is what lets the same job run on a tiny budget of memory.

The story: The Tiffin That Got Lighter

Mira's mother packed three stacked steel tiffin boxes every morning, and by the time Mira reached school the stack felt like a bag of bricks. "Why do I carry the boxes I have finished?" she groaned. "Yesterday's, and the day before's. I only need to eat from the top three!"

Back home, Kabir was solving a stair puzzle with hops of 1, 2 or 3 steps. His notebook had a long table: one row for every step up to 1000. Mira peeked and noticed the same thing: "To fill row 500, you only look at rows 499, 498 and 497. Why keep rows 1 to 496?"

They crossed out every row except the newest three and just rewrote them as the loop moved on. The same answer came out, but the notebook had shrunk from a thousand rows to three. Mira's bag, thankfully, also got lighter when she started leaving the empty boxes at school.

This is space optimization: once you know which earlier answers a box depends on, keep only those. The table becomes a few variables (or one row of a grid), and the memory cost often drops from "grows with n" to "a tiny fixed number".

How to spot this problem, and where you need it

Your solution is correct but uses far too much memory, or the server runs out of memory on large inputs, even though each step only looks at a few earlier values.

Signs you need it

  • Your table is a big array or grid, but each cell only reads the previous row or the previous one or two values.
  • The process is killed with an out-of-memory error, or memory climbs steeply with input size.
  • You only need the final answer, not the full table or the path that led to it.

Where to use it in a project

  • File comparison, log diffing and text similarity features working on large uploads.
  • Long running totals, schedules or scores calculated over thousands of periods.

The solution

Look at which earlier cells the transition reads. If it reads only the previous row, keep two rows and swap them after each pass. If it reads only the last two values, keep two variables and shift them forward. Replace the full table with those few variables. Note that you can no longer rebuild the full path afterwards, only the final number.

Payoff: Before: a table with 10 billion cells and an out-of-memory crash. After: two rows of 100,000 cells each and the job finishes normally.

Explain it like I am 8

You are walking on stepping stones, but each stone vanishes behind you after you step off. You only ever need the stones right behind your feet. So you carry only the last few instead of the whole river.

How it works, step by step

  1. First solve it with a full table and get it correct. Optimising a wrong solution just makes a smaller wrong solution.
  2. Look at the transition. How far back does a box reach? One step back, two, a whole previous row?
  3. Keep only that window. Use plain variables (a, b, c) for a few boxes, or one array for the previous row.
  4. Slide forward each turn: shift the variables (a = b; b = c; c = new), oldest value gone.
  5. Trade-off: you can no longer look at old boxes, so rebuilding the actual chosen path needs the full table (or extra tracking).

The code in four languages

PHP

<?php
// Ways to climb n steps using hops of 1, 2 or 3. Only the last three answers matter.
function waysThreeHops(int $n): int {
    if ($n <= 1) return 1;
    if ($n === 2) return 2;
    $a = 1;      // ways[i-3]  (starts as ways[0])
    $b = 1;      // ways[i-2]  (starts as ways[1])
    $c = 2;      // ways[i-1]  (starts as ways[2])
    for ($i = 3; $i <= $n; $i++) {
        $next = $a + $b + $c;     // the transition
        $a = $b;                  // slide the window: oldest answer is forgotten
        $b = $c;
        $c = $next;
    }
    return $c;                    // three variables instead of an array of n + 1
}

echo waysThreeHops(10), "\n";    // 274
echo waysThreeHops(3), "\n";     // 4

JavaScript

// Ways to climb n steps using hops of 1, 2 or 3. Only the last three answers matter.
function waysThreeHops(n) {
  if (n <= 1) return 1;
  if (n === 2) return 2;
  let a = 1;      // ways[i-3]  (starts as ways[0])
  let b = 1;      // ways[i-2]  (starts as ways[1])
  let c = 2;      // ways[i-1]  (starts as ways[2])
  for (let i = 3; i <= n; i++) {
    const next = a + b + c;       // the transition
    a = b;                        // slide the window: oldest answer is forgotten
    b = c;
    c = next;
  }
  return c;                       // three variables instead of an array of n + 1
}

console.log(waysThreeHops(10));   // 274
console.log(waysThreeHops(3));    // 4

Java

public class Main {
    // Ways to climb n steps using hops of 1, 2 or 3. Only the last three answers matter.
    static int waysThreeHops(int n) {
        if (n <= 1) return 1;
        if (n == 2) return 2;
        int a = 1;      // ways[i-3]  (starts as ways[0])
        int b = 1;      // ways[i-2]  (starts as ways[1])
        int c = 2;      // ways[i-1]  (starts as ways[2])
        for (int i = 3; i <= n; i++) {
            int next = a + b + c;     // the transition
            a = b;                    // slide the window: oldest answer is forgotten
            b = c;
            c = next;
        }
        return c;                     // three variables instead of an array of n + 1
    }

    public static void main(String[] args) {
        System.out.println(waysThreeHops(10));    // 274
        System.out.println(waysThreeHops(3));     // 4
    }
}

Go

package main

import "fmt"

// Ways to climb n steps using hops of 1, 2 or 3. Only the last three answers matter.
func waysThreeHops(n int) int {
	if n <= 1 {
		return 1
	}
	if n == 2 {
		return 2
	}
	a := 1 // ways[i-3]  (starts as ways[0])
	b := 1 // ways[i-2]  (starts as ways[1])
	c := 2 // ways[i-1]  (starts as ways[2])
	for i := 3; i <= n; i++ {
		next := a + b + c // the transition
		a = b             // slide the window: oldest answer is forgotten
		b = c
		c = next
	}
	return c // three variables instead of an array of n + 1
}

func main() {
	fmt.Println(waysThreeHops(10)) // 274
	fmt.Println(waysThreeHops(3))  // 4
}

Time: O(n) · Extra space: O(1). The time does not change, but memory drops from a table that grows with n to just three boxes.

Watch out for

  • Overwriting a variable before the next one has read it (for example a = b after b = c). Shift oldest-first.
  • Optimising too early. First get a correct full-table solution, then shrink it.
  • Shrinking the table and then trying to rebuild the chosen path from it. The old boxes are gone, so keep extra information if you need the path.

Quick check

  1. When is space optimization possible?
    • When each box depends only on a few recent boxes
    • Only for sorted input
    • Never
  2. How much memory does the 1-2-3 hop solution need?
    • Memory growing with n
    • About n squared boxes
    • Three variables
  3. What does space optimization change about the running time?
    • It makes it much worse
    • Usually nothing; it is the memory that shrinks
    • It makes the program run backwards