AlgoTales · Roadmap

Suffix sums

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A suffix sum list stores, at each position, the total of everything from that position to the end. It answers how much is left questions at once, such as stock remaining, runs still needed or minutes left in a playlist, with a quick lookup.

Practical use cases

  • Web app: Remaining stock across warehouses. A shop lists warehouses in delivery order and wants to know how many units remain from warehouse 3 onward. Instead of adding the later warehouses each time, the page keeps a from-here-to-the-end total next to each one and just reads it.
  • Web app: Time left on a playlist or course. A learning site shows 3 hours 20 minutes left in this course as the student moves through lessons. Keeping a from-here-to-the-end total of lesson lengths means the number updates the moment the student opens the next lesson, without adding lessons again. A long course with 200 lessons costs the same single lookup as a short one.
  • System: Balance-point and match projections. Cricket projections need the runs still to come from each over onward, and some puzzles ask where the left side equals the right side. A suffix list gives the right-hand total at any point immediately, so projections for every over can be shown without recalculating anything.

The story: Runs Still to Come

The school cricket coach, Mr. Iyer, had a habit. Every over he shouted, "How many runs have we planned to score from this over till the end?" Aarav, the scorer, kept adding the remaining overs again and again. In a long match his pencil was always busy.

Zoya, the quiet girl who sat with the scorebook, said, "Sir, let me prepare a second row. I will start from the last over and walk backward. Each box will hold the total of everything from that over to the end."

She wrote the last over's runs first. Then, for the over before, she added that over to the box she had just written. Every new box took one addition. After one backward walk, her second row had the answer to the coach's question for every over.

Now the coach asked, "From over 2?" and Zoya just pointed at a box. That second row is called a suffix sum: each position stores the total from there to the end of the array. It is the mirror image of the prefix sums you met earlier.

How to spot this problem, and where you need it

You keep asking how much is left from this point to the end of a list, and recomputing the total of the remaining items each time makes your code slow or repetitive.

Signs you need it

  • The question is phrased as remaining, still to go, from here on, or everything after this position.
  • You loop forward from the current position to the end inside another loop over positions.
  • A problem asks for a point where the sum on the left equals the sum on the right.

Where to use it in a project

  • Progress and remaining-time displays on course sites, video playlists and download queues.
  • Inventory and planning screens showing what is left after each step of a sequence, such as delivery routes.

The solution

Walk the list from the right end to the left. At the last position, the suffix total is just that item. At every earlier position, it is the item plus the suffix total of the next position. Keep these totals in an array. To find how much remains from position k, read the value at k. Combine it with the total of everything to compare left and right.

Payoff: Before: re-adding the rest of the list for every lesson or over. After: one right-to-left pass, then each remaining total is a single read.

Explain it like I am 8

Put coins in a row. Starting from the far right, write under each coin how many coins lie from there to the right end. Next time someone asks "how many from here on?", just read the number under it.

How it works, step by step

  1. Make a second array suffix of the same size.
  2. The last box is just the last number: suffix[n-1] = a[n-1].
  3. Walk right to left: suffix[i] = a[i] + suffix[i+1].
  4. To get "everything from index i to the end", read suffix[i].
  5. To get a middle range, subtract: suffix[l] - suffix[r+1] (treat the box past the end as 0).

The code in four languages

PHP

<?php
// suffix[i] = sum of a[i] .. a[n-1]
function buildSuffix(array $a): array {
    $n = count($a);
    $suffix = array_fill(0, $n, 0);
    $running = 0;
    for ($i = $n - 1; $i >= 0; $i--) {    // walk right to left
        $running += $a[$i];
        $suffix[$i] = $running;
    }
    return $suffix;
}

$runs = [3, 1, 4, 1, 5];
$suffix = buildSuffix($runs);
echo implode(', ', $suffix) . PHP_EOL;        // 14, 11, 10, 6, 5
echo "From over 2: " . $suffix[2] . PHP_EOL;  // 10

// Range sum of overs 1..2 = suffix[1] - suffix[3]
echo "Overs 1..2: " . ($suffix[1] - $suffix[3]) . PHP_EOL;   // 5

JavaScript

// suffix[i] = sum of a[i] .. a[n-1]
function buildSuffix(a) {
  const n = a.length;
  const suffix = new Array(n).fill(0);
  let running = 0;
  for (let i = n - 1; i >= 0; i--) {     // walk right to left
    running += a[i];
    suffix[i] = running;
  }
  return suffix;
}

const runs = [3, 1, 4, 1, 5];
const suffix = buildSuffix(runs);
console.log(suffix.join(', '));          // 14, 11, 10, 6, 5
console.log('From over 2: ' + suffix[2]); // 10

// Range sum of overs 1..2 = suffix[1] - suffix[3]
console.log('Overs 1..2: ' + (suffix[1] - suffix[3]));   // 5

Java

import java.util.*;

public class Main {
    // suffix[i] = sum of a[i] .. a[n-1]
    static int[] buildSuffix(int[] a) {
        int n = a.length;
        int[] suffix = new int[n];
        int running = 0;
        for (int i = n - 1; i >= 0; i--) {    // walk right to left
            running += a[i];
            suffix[i] = running;
        }
        return suffix;
    }

    public static void main(String[] args) {
        int[] runs = {3, 1, 4, 1, 5};
        int[] suffix = buildSuffix(runs);
        System.out.println(Arrays.toString(suffix));         // [14, 11, 10, 6, 5]
        System.out.println("From over 2: " + suffix[2]);     // 10

        // Range sum of overs 1..2 = suffix[1] - suffix[3]
        System.out.println("Overs 1..2: " + (suffix[1] - suffix[3]));   // 5
    }
}

Go

package main

import "fmt"

// buildSuffix: suffix[i] = sum of a[i] .. a[n-1].
func buildSuffix(a []int) []int {
	n := len(a)
	suffix := make([]int, n)
	running := 0
	for i := n - 1; i >= 0; i-- { // walk right to left
		running += a[i]
		suffix[i] = running
	}
	return suffix
}

func main() {
	runs := []int{3, 1, 4, 1, 5}
	suffix := buildSuffix(runs)
	fmt.Println(suffix)                    // [14 11 10 6 5]
	fmt.Println("From over 2:", suffix[2]) // 10

	// Range sum of overs 1..2 = suffix[1] - suffix[3]
	fmt.Println("Overs 1..2:", suffix[1]-suffix[3]) // 5
}

Time: O(n) to build, O(1) per question · Extra space: O(n). One backward pass pays for unlimited instant answers afterwards.

Watch out for

  • Walking left to right. A suffix box needs the box to its right to be ready first.
  • Reading past the end (suffix[n]) when a range ends at the last item. Treat it as 0 or keep one spare box.
  • Rebuilding the suffix array for every question, which loses the whole benefit.

Quick check

  1. In which direction do we build a suffix-sum array?
    • Right to left
    • Left to right
    • Either, it is the same
  2. For [3, 1, 4, 1, 5], what is suffix[3]?
    • 1
    • 5
    • 6
  3. How long does each "sum from i to the end" question take after building?
    • O(n)
    • O(log n)
    • O(1)