Coding Interview Patterns Module 6 – Prefix sums and difference arrays
Prefix sums for instant range totals
Build a prefix-sum array with a 0 in front, answer any range total with one subtraction, keep large totals exact, and spot prefix sums inside other problems.
What you will learn
- Build a prefix array with a leading zero to avoid off-by-one errors
- Answer range-sum queries in O(1) after one pass of preparation
- Size the integer type of the totals from the largest prefix the limits allow
- Recognise prefix sums inside other problems, such as finding a balance point
Before you start
What you’ll learn · Before you start
What you will learn
- Build a prefix array with a leading zero to avoid off-by-one errors
- Answer range-sum queries in O(1) after one pass of preparation
- Size the integer type of the totals from the largest prefix the limits allow
- Recognise prefix sums inside other problems, such as finding a balance point
Before you start
On this page
A shop’s accounts page asks for the total sales between two days up to 200,000 times over a ledger of 200,000 days;
adding up each range again costs up to 4 × 10¹⁰ additions. A prefix sum array: The running totals of a list with a 0 in front: prefix[0] = 0 and prefix[i + 1] = prefix[i] + a[i], so prefix[i] is the total of the first i items and any range total is one subtraction. array holds the
running totals of a list, with a 0 in front: prefix[0] = 0 and prefix[i + 1] = prefix[i] + a[i], so prefix[i] is
the total of the first i items. The total of any stretch, from item first to item last, is then one subtraction,
prefix[last + 1] - prefix[first], however long the stretch is. Building the array takes one pass over the list,
O(n), and every range total after that costs O(1). Reach for it when a list that does not change is asked many
questions of the form “what is the total from here to there?”.
Below, one problem is solved in full, in 14 languages, and the same idea then turns up in a problem that never mentions ranges.
Running totals: a 0 in front makes every range one subtraction
A small shop writes down what it took each day. The loop below builds the prefix list for the first week of its
ledger, one entry a day, then reads one range from it. Step through it and watch prefix grow:
Program · trace/build_prefix.py
sales = [420, 380, 0, 515, 610, 290, 700]
prefix = [0]
for amount in sales:
prefix.append(prefix[-1] + amount)
first, last = 2, 4
total = prefix[last + 1] - prefix[first]
print(prefix)
print(total) Variables
- just taken by the loop
- changed in this step
- passed by the loop
- read next
- where the loop stopped
Printed so far
Nothing printed yet[0, 420, 800, 800, 1315, 1925, 2215, 2915] 1125
Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.
The drawing shows the variables when the program ends, and the program's 22 steps are listed below.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 1.
- Line 1.
sales = [420, 380, 0, 515, 610, 290, 700]makessalesa list of 7 items. - Line 2.
prefix = [0]makesprefixa list of 1 item. Key point prefix starts as [0], the total of no days at all. Every entry the loop adds is the entry before it plus one more day of sales. - Line 3.
for amount in sales:takes the item at position 0 ofsales:amountis420. - Line 4.
prefix.append(prefix[-1] + amount)adds420to the end ofprefix. - Line 3.
for amount in sales:takes the item at position 1 ofsales:amountis380. - Line 4.
prefix.append(prefix[-1] + amount)adds800to the end ofprefix. - Line 3.
for amount in sales:takes the item at position 2 ofsales:amountis0. - Line 4.
prefix.append(prefix[-1] + amount)adds800to the end ofprefix. Day 2 sold nothing, so the new entry is 800 again. Two equal neighbours in prefix always mean a day with no sales. - Line 3.
for amount in sales:takes the item at position 3 ofsales:amountis515. - Line 4.
prefix.append(prefix[-1] + amount)adds1315to the end ofprefix. - Line 3.
for amount in sales:takes the item at position 4 ofsales:amountis610. - Line 4.
prefix.append(prefix[-1] + amount)adds1925to the end ofprefix. - Line 3.
for amount in sales:takes the item at position 5 ofsales:amountis290. - Line 4.
prefix.append(prefix[-1] + amount)adds2215to the end ofprefix. - Line 3.
for amount in sales:takes the item at position 6 ofsales:amountis700. - Line 4.
prefix.append(prefix[-1] + amount)adds2915to the end ofprefix. - Line 3.
for amount in sales:finds no item at position 7 ofsales(it has 7 items), so the loop ends. - Line 5.
first, last = 2, 4setsfirstto2and setslastto4. - Line 6.
total = prefix[last + 1] - prefix[first]setstotalto1125. Key point Days 2 to 4 are prefix[5] − prefix[2] = 1,925 − 800 = 1,125: the first two days are in both entries, so they cancel. - Line 7.
print(prefix)prints[0, 420, 800, 800, 1315, 1925, 2215, 2915]. - Line 8.
print(total)prints1125. That was the last line, so the program ends.
Here are all 14 days of the ledger, with the prefix list built by a loop and again by itertools.accumulate, and four
questions about it:
from itertools import accumulate
# What a small shop took on each of 14 days, day 0 first.
sales = [420, 380, 0, 515, 610, 290, 700, 455, 390, 660, 0, 530, 480, 625]
# prefix[i] is the total of the first i days: prefix[0] = 0, and prefix has one entry more than sales.
prefix = [0]
for amount in sales:
prefix.append(prefix[-1] + amount)
print("sales: ", sales)
print("prefix:", prefix)
print("the same list from accumulate:", list(accumulate(sales, initial=0)) == prefix)
def total(first, last):
"""The sales from day `first` to day `last`, both days included."""
return prefix[last + 1] - prefix[first]
for first, last in [(2, 4), (7, 13), (0, 10), (3, 3)]:
print(f"days {first} to {last}: {total(first, last)}")
# Without the 0 in front, running[i] covers days 0 to i, and a range starting on day 0 needs a special case.
# Forget it, and running[first - 1] is running[-1]: Python reads the last entry instead of failing.
running = list(accumulate(sales))
print("days 0 to 2 without the 0 in front:", running[2] - running[0 - 1]) Output
sales: [420, 380, 0, 515, 610, 290, 700, 455, 390, 660, 0, 530, 480, 625] prefix: [0, 420, 800, 800, 1315, 1925, 2215, 2915, 3370, 3760, 4420, 4420, 4950, 5430, 6055] the same list from accumulate: True days 2 to 4: 1125 days 7 to 13: 3140 days 0 to 10: 4420 days 3 to 3: 515 days 0 to 2 without the 0 in front: -5255
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 ledger.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
The prefix list has 15 entries for 14 days. prefix[5] is 1,925, the total of the first five days, days 0 to 4, and
prefix[2] is 800, the total of days 0 and 1. Their difference is what days 2 to 4 add on top of the first two
days, and that is the answer to the first question:
One subtraction gives the total of a range
Text description of the diagram
The diagram shows one large box with two smaller boxes inside it, and an arrow to a result below.
- The large box is prefix[5] = 1,925, the total of the first five days, days 0 to 4.
- Inside it, on the left, is prefix[2] = 800, the total of days 0 and 1 (420 + 380).
- Inside it, on the right, are days 2 to 4: 0 + 515 + 610 = 1,125.
- An arrow from the right-hand box leads to the result: what is left once prefix[2] is taken away. Days 2 to 4 total prefix[5] − prefix[2] = 1,925 − 800 = 1,125.
The same subtraction answers every question, from the second week to a single day. “Month to date on day 10” is
the range from day 0 to day 10, and it needs no special case: prefix[0] is 0, so nothing is taken away.
accumulate(sales, initial=0) builds the same list in one call. The initial argument arrived in Python 3.8, and
the documentation says that with it the output has one more element than the input, which is exactly the 0 in front.
Without it, accumulate gives the totals of days 0 to i, and a range that starts on day 0 needs an if. The last
line of the output shows what happens when that if is forgotten: running[0 - 1] is running[-1], which Python
reads as the last entry of the list, so the program prints a negative total and raises no error.
Checkpoint
Check: Running totals with a 0 in front
The problem: adding up every range again is too slow
The problem below is the one this module’s pattern was made for. Here it is worked in full, in the order a coding round asks for: the brute force, what to notice, the fast version, why it is correct, a dry run, the cost, code, a stress test, edge cases and follow-up questions.
The problem
A shop’s ledger lists what it took on each day, sales[0] to sales[n - 1]. Its accounts page asks many
questions of one kind: what were the total sales from day first to day last, both days included? Write
range_totals(sales, queries), which returns the answer to every query, in order. There are 1 to 200,000 days
and 1 to 200,000 queries, each day’s sales are a whole number from 0 to 10⁹, and every query has
0 ≤ first ≤ last ≤ n − 1.
For the first week of the ledger above, sales = [420, 380, 0, 515, 610, 290, 700], and the queries (2, 4), (0, 6),
(3, 3), (0, 0) and (6, 6) have the answers 1,125, 2,915, 515, 420 and 700. Each query is a
range query: A question about a contiguous stretch of a list, such as the total or the count of the items from position first to position last, both included..
Brute force first
Add up the days of each query again:
def range_totals_brute(sales, queries):
"""Adds up the days of every query again: up to n additions per query."""
answers = []
for first, last in queries:
total = 0
for day in range(first, last + 1):
total += sales[day]
answers.append(total)
return answers
if __name__ == "__main__":
sales = [420, 380, 0, 515, 610, 290, 700]
print(range_totals_brute(sales, [(2, 4), (0, 6), (3, 3), (0, 0), (6, 6)])) Output
[1125, 2915, 515, 420, 700]
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 brute.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
It is correct by construction, and it is slow. A query can cover the whole ledger, so each one costs up to n additions and all of them cost O(n × q). At the limits that is up to 200,000 × 200,000 = 4 × 10¹⁰ additions. Even compiled code, budgeted at 10⁸ simple steps a second as in the lesson on reading constraints, would need about 400 seconds, against a time limit of a second or two. Keep the brute force anyway: it checks the fast version below.
What to notice
The ledger never changes between queries, yet the brute force adds the same days again and again: every query that
covers day 3 adds sales[3] once more. That is the cue for prefix sums. Look for three things together: many
queries, each asking for a total (or a count) over a contiguous range, on data that stays the same while the queries
run. Do the shared work once, as running totals, and each query becomes a lookup.
Checkpoint
Check: The brute force and the cue for prefix sums
The fast version: one pass to build, one subtraction per query
- Make a list
prefixof n + 1 zeros. - In one pass over the days, set
prefix[day + 1] = prefix[day] + sales[day]. - Answer each query
(first, last)withprefix[last + 1] - prefix[first].
Here it is in 14 languages. Every tab holds the same program, and every one of them printed the lines under the tabs:
Python 3.14 · main.py
def range_totals(sales: list[int], queries: list[tuple[int, int]]) -> list[int]:
# prefix[i] is the total of the first i days, so prefix[0] = 0.
prefix = [0] * (len(sales) + 1)
for day, amount in enumerate(sales):
prefix[day + 1] = prefix[day] + amount
return [prefix[last + 1] - prefix[first] for first, last in queries]
sales = [420, 380, 0, 515, 610, 290, 700]
queries = [(2, 4), (0, 6), (3, 3), (0, 0), (6, 6)]
print(range_totals(sales, queries))
# The largest ledger the limits allow: 200,000 days of 1,000,000,000 each.
big = [1_000_000_000] * 200_000
print(range_totals(big, [(0, 199_999)])[0]) In Python: itertools.accumulate(sales, initial=0) builds the same list in one call; the loop is written out so that every language takes the same steps. A Python int has no upper limit, so 2 × 10¹⁴ needs no special type.
Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py
JavaScript Node 24 · main.mjs
function rangeTotals(sales, queries) {
// prefix[i] is the total of the first i days, so prefix[0] = 0.
const prefix = new Array(sales.length + 1).fill(0);
for (let day = 0; day < sales.length; day++) {
prefix[day + 1] = prefix[day] + sales[day];
}
return queries.map(([first, last]) => prefix[last + 1] - prefix[first]);
}
const sales = [420, 380, 0, 515, 610, 290, 700];
const queries = [
[2, 4],
[0, 6],
[3, 3],
[0, 0],
[6, 6],
];
console.log(`[${rangeTotals(sales, queries).join(", ")}]`);
// The largest ledger the limits allow: 200,000 days of 1,000,000,000 each.
const big = new Array(200_000).fill(1_000_000_000);
console.log(rangeTotals(big, [[0, 199_999]])[0]); In JavaScript: A Number holds every whole number up to 2⁵³ − 1 exactly, about 9 × 10¹⁵, so the total of 2 × 10¹⁴ is exact; Number.isSafeInteger(total) would confirm it.
Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs
Java 25 LTS · Main.java
import java.util.Arrays;
public class Main {
record Query(int first, int last) {}
static long[] rangeTotals(int[] sales, Query[] queries) {
// prefix[i] is the total of the first i days, so prefix[0] = 0.
long[] prefix = new long[sales.length + 1];
for (int day = 0; day < sales.length; day++) {
prefix[day + 1] = prefix[day] + sales[day];
}
long[] answers = new long[queries.length];
for (int i = 0; i < queries.length; i++) {
answers[i] = prefix[queries[i].last() + 1] - prefix[queries[i].first()];
}
return answers;
}
public static void main(String[] args) {
int[] sales = {420, 380, 0, 515, 610, 290, 700};
Query[] queries = {
new Query(2, 4), new Query(0, 6), new Query(3, 3), new Query(0, 0), new Query(6, 6)
};
System.out.println(Arrays.toString(rangeTotals(sales, queries)));
// The largest ledger the limits allow: 200,000 days of 1,000,000,000 each.
int[] big = new int[200_000];
Arrays.fill(big, 1_000_000_000);
System.out.println(rangeTotals(big, new Query[] {new Query(0, 199_999)})[0]);
}
} In Java: The sales stay int, since each day fits, and Java widens each one when it is added to the long prefix. An int[] prefix would wrap around, as the section on overflow shows.
Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java
C++23 · main.cpp
#include <cstdint>
#include <numeric>
#include <print>
#include <utility>
#include <vector>
std::vector<std::int64_t>
range_totals(const std::vector<std::int64_t> &sales,
const std::vector<std::pair<int, int>> &queries) {
// prefix[i] is the total of the first i days, so prefix[0] = 0.
std::vector<std::int64_t> prefix(sales.size() + 1, 0);
std::partial_sum(sales.begin(), sales.end(), prefix.begin() + 1);
std::vector<std::int64_t> answers;
answers.reserve(queries.size());
for (const auto &[first, last] : queries) {
answers.push_back(prefix[last + 1] - prefix[first]);
}
return answers;
}
int main() {
const std::vector<std::int64_t> sales = {420, 380, 0, 515, 610, 290, 700};
const std::vector<std::pair<int, int>> queries = {
{2, 4}, {0, 6}, {3, 3}, {0, 0}, {6, 6}};
std::println("{}", range_totals(sales, queries));
// The largest ledger the limits allow: 200,000 days of 1,000,000,000 each.
const std::vector<std::int64_t> big(200'000, 1'000'000'000);
std::println("{}", range_totals(big, {{0, 199'999}})[0]);
} In C++: std::partial_sum from <numeric> writes the running totals from prefix.begin() + 1, so prefix[0] stays 0, and std::println prints the vector of answers as a list, new in C++23.
Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main
C# 14 · .NET 10 · app.cs
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
long[] sales = [420, 380, 0, 515, 610, 290, 700];
(int First, int Last)[] queries = [(2, 4), (0, 6), (3, 3), (0, 0), (6, 6)];
Console.WriteLine($"[{string.Join(", ", RangeTotals(sales, queries))}]");
// The largest ledger the limits allow: 200,000 days of 1,000,000,000 each.
long[] big = Enumerable.Repeat(1_000_000_000L, 200_000).ToArray();
Console.WriteLine(RangeTotals(big, [(0, 199_999)])[0]);
static long[] RangeTotals(long[] sales, (int First, int Last)[] queries)
{
// prefix[i] is the total of the first i days, so prefix[0] = 0.
var prefix = new long[sales.Length + 1];
for (int day = 0; day < sales.Length; day++)
{
prefix[day + 1] = prefix[day] + sales[day];
}
return [.. queries.Select(q => prefix[q.Last + 1] - prefix[q.First])];
} In C#: long is 64 bits wide; Enumerable.Repeat builds the large ledger, and the collection expression [.. ] turns the selected answers into an array.
Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs
C23 · main.c
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
size_t first;
size_t last;
} Query;
// Writes the answer to each query into answers; false if memory runs out.
static bool range_totals(const int64_t *sales, size_t days,
const Query *queries, size_t count, int64_t *answers) {
// prefix[i] is the total of the first i days, so prefix[0] = 0.
int64_t *prefix = calloc(days + 1, sizeof *prefix);
if (prefix == nullptr) {
return false;
}
for (size_t day = 0; day < days; day++) {
prefix[day + 1] = prefix[day] + sales[day];
}
for (size_t i = 0; i < count; i++) {
answers[i] = prefix[queries[i].last + 1] - prefix[queries[i].first];
}
free(prefix);
return true;
}
enum { QUERIES = 5, BIG_DAYS = 200000 };
int main(void) {
static const int64_t sales[] = {420, 380, 0, 515, 610, 290, 700};
static const Query queries[QUERIES] = {
{2, 4}, {0, 6}, {3, 3}, {0, 0}, {6, 6}};
int64_t answers[QUERIES];
if (!range_totals(sales, sizeof sales / sizeof sales[0], queries, QUERIES,
answers)) {
return 1;
}
printf("[");
for (size_t i = 0; i < QUERIES; i++) {
printf("%s%" PRId64, i == 0 ? "" : ", ", answers[i]);
}
printf("]\n");
// The largest ledger the limits allow: 200,000 days of 1,000,000,000 each.
static int64_t big[BIG_DAYS];
for (size_t day = 0; day < BIG_DAYS; day++) {
big[day] = 1000000000;
}
const Query whole = {0, BIG_DAYS - 1};
int64_t total = 0;
if (!range_totals(big, BIG_DAYS, &whole, 1, &total)) {
return 1;
}
printf("%" PRId64 "\n", total);
return 0;
} In C: C has no growable list, so calloc makes the n + 1 zeroed totals and free returns them; int64_t from <stdint.h> holds the large total, printed with PRId64.
Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main
PHP 8.5 · main.php
<?php
declare(strict_types=1);
/**
* @param list<int> $sales
* @param list<array{int, int}> $queries
* @return list<int>
*/
function rangeTotals(array $sales, array $queries): array
{
// prefix[i] is the total of the first i days, so prefix[0] = 0.
$prefix = [0];
foreach ($sales as $day => $amount) {
$prefix[$day + 1] = $prefix[$day] + $amount;
}
return array_map(fn(array $q): int => $prefix[$q[1] + 1] - $prefix[$q[0]], $queries);
}
$sales = [420, 380, 0, 515, 610, 290, 700];
$queries = [[2, 4], [0, 6], [3, 3], [0, 0], [6, 6]];
echo '[' . implode(', ', rangeTotals($sales, $queries)) . "]\n";
// The largest ledger the limits allow: 200,000 days of 1,000,000,000 each.
$big = array_fill(0, 200_000, 1_000_000_000);
echo rangeTotals($big, [[0, 199_999]])[0], "\n"; In PHP: An int is 64 bits wide in this PHP, so the totals need no special type; array_map with an arrow function answers the queries.
Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. To run it yourself: php main.php
Rust 1.99 · main.rs
fn range_totals(sales: &[i64], queries: &[(usize, usize)]) -> Vec<i64> {
// prefix[i] is the total of the first i days, so prefix[0] = 0.
let mut prefix = vec![0; sales.len() + 1];
for (day, amount) in sales.iter().enumerate() {
prefix[day + 1] = prefix[day] + amount;
}
queries
.iter()
.map(|&(first, last)| prefix[last + 1] - prefix[first])
.collect()
}
fn main() {
let sales = [420, 380, 0, 515, 610, 290, 700];
let queries = [(2, 4), (0, 6), (3, 3), (0, 0), (6, 6)];
println!("{:?}", range_totals(&sales, &queries));
// The largest ledger the limits allow: 200,000 days of 1,000,000,000 each.
let big = vec![1_000_000_000; 200_000];
println!("{}", range_totals(&big, &[(0, 199_999)])[0]);
} In Rust: vec![0; n + 1] takes its element type, i64, from the sales added into it, and the closure takes each (first, last) apart by pattern; {:?} prints the vector of answers.
Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main
TypeScript 6.0 · main.ts
function rangeTotals(sales: number[], queries: [number, number][]): number[] {
// prefix[i] is the total of the first i days, so prefix[0] = 0.
const prefix: number[] = new Array<number>(sales.length + 1).fill(0);
for (let day = 0; day < sales.length; day++) {
prefix[day + 1] = prefix[day] + sales[day];
}
return queries.map(([first, last]) => prefix[last + 1] - prefix[first]);
}
const sales = [420, 380, 0, 515, 610, 290, 700];
const queries: [number, number][] = [
[2, 4],
[0, 6],
[3, 3],
[0, 0],
[6, 6],
];
console.log(`[${rangeTotals(sales, queries).join(", ")}]`);
// The largest ledger the limits allow: 200,000 days of 1,000,000,000 each.
const big: number[] = new Array<number>(200_000).fill(1_000_000_000);
console.log(rangeTotals(big, [[0, 199_999]])[0]); In TypeScript: The tuple type [number, number][] lets tsc check every query; the numbers are the same doubles as in JavaScript, exact up to 2⁵³ − 1.
Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts
Go 1.27 · main.go
package main
import (
"fmt"
"strconv"
"strings"
)
type query struct{ first, last int }
func rangeTotals(sales []int64, queries []query) []int64 {
// prefix[i] is the total of the first i days, so prefix[0] = 0.
prefix := make([]int64, len(sales)+1)
for day, amount := range sales {
prefix[day+1] = prefix[day] + amount
}
answers := make([]int64, len(queries))
for i, q := range queries {
answers[i] = prefix[q.last+1] - prefix[q.first]
}
return answers
}
func main() {
sales := []int64{420, 380, 0, 515, 610, 290, 700}
queries := []query{{2, 4}, {0, 6}, {3, 3}, {0, 0}, {6, 6}}
parts := []string{}
for _, total := range rangeTotals(sales, queries) {
parts = append(parts, strconv.FormatInt(total, 10))
}
fmt.Printf("[%s]\n", strings.Join(parts, ", "))
// The largest ledger the limits allow: 200,000 days of 1,000,000,000 each.
big := make([]int64, 200_000)
for day := range big {
big[day] = 1_000_000_000
}
fmt.Println(rangeTotals(big, []query{{0, 199_999}})[0])
} In Go: The specification lets int be 32 or 64 bits wide, so the totals are int64; Println would print the slice without commas, so the answers are joined by hand.
Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go
Swift 6.4 · main.swift
func rangeTotals(of sales: [Int64], for queries: [(first: Int, last: Int)]) -> [Int64] {
// prefix[i] is the total of the first i days, so prefix[0] = 0.
var prefix = [Int64](repeating: 0, count: sales.count + 1)
for (day, amount) in sales.enumerated() {
prefix[day + 1] = prefix[day] + amount
}
return queries.map { prefix[$0.last + 1] - prefix[$0.first] }
}
let sales: [Int64] = [420, 380, 0, 515, 610, 290, 700]
let queries: [(first: Int, last: Int)] = [(2, 4), (0, 6), (3, 3), (0, 0), (6, 6)]
print(rangeTotals(of: sales, for: queries))
// The largest ledger the limits allow: 200,000 days of 1,000,000,000 each.
let big = [Int64](repeating: 1_000_000_000, count: 200_000)
print(rangeTotals(of: big, for: [(first: 0, last: 199_999)])[0]) In Swift: Int64 keeps the totals 64 bits wide on every platform, the WebAssembly build included, where Int has 32 bits; the queries are labelled tuples.
Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main
Ruby 4.0 · main.rb
# frozen_string_literal: true
def range_totals(sales, queries)
# prefix[i] is the total of the first i days, so prefix[0] = 0.
prefix = [0]
sales.each { |amount| prefix << (prefix.last + amount) }
queries.map { |first, last| prefix[last + 1] - prefix[first] }
end
sales = [420, 380, 0, 515, 610, 290, 700]
queries = [[2, 4], [0, 6], [3, 3], [0, 0], [6, 6]]
puts "[#{range_totals(sales, queries).join(', ')}]"
# The largest ledger the limits allow: 200,000 days of 1,000,000,000 each.
big = Array.new(200_000, 1_000_000_000)
puts range_totals(big, [[0, 199_999]]).first In Ruby: Integers grow past 64 bits on their own, and prefix.last reads the newest total; summing a slice for each query would be the brute force again.
Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb
Kotlin 2.4 · Main.kt
fun rangeTotals(
sales: LongArray,
queries: List<Pair<Int, Int>>,
): List<Long> {
// prefix[i] is the total of the first i days, so prefix[0] = 0.
val prefix = LongArray(sales.size + 1)
for (day in sales.indices) {
prefix[day + 1] = prefix[day] + sales[day]
}
return queries.map { (first, last) -> prefix[last + 1] - prefix[first] }
}
fun main() {
val sales = longArrayOf(420, 380, 0, 515, 610, 290, 700)
val queries = listOf(2 to 4, 0 to 6, 3 to 3, 0 to 0, 6 to 6)
println(rangeTotals(sales, queries))
// The largest ledger the limits allow: 200,000 days of 1,000,000,000 each.
val big = LongArray(200_000) { 1_000_000_000L }
println(rangeTotals(big, listOf(0 to 199_999))[0])
} In Kotlin: LongArray holds the 64-bit totals, and the lambda takes each Pair apart into first and last; println prints the list of answers.
Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar
Dart 3.13 · main.dart
List<int> rangeTotals(List<int> sales, List<(int, int)> queries) {
// prefix[i] is the total of the first i days, so prefix[0] = 0.
final prefix = List<int>.filled(sales.length + 1, 0);
for (var day = 0; day < sales.length; day++) {
prefix[day + 1] = prefix[day] + sales[day];
}
return [
for (final (first, last) in queries) prefix[last + 1] - prefix[first],
];
}
void main() {
final sales = [420, 380, 0, 515, 610, 290, 700];
final queries = [(2, 4), (0, 6), (3, 3), (0, 0), (6, 6)];
print(rangeTotals(sales, queries));
// The largest ledger the limits allow: 200,000 days of 1,000,000,000 each.
final big = List<int>.filled(200000, 1000000000);
print(rangeTotals(big, [(0, 199999)])[0]);
} In Dart: An int is a signed 64-bit integer on native platforms such as the Dart VM, so the totals fit; a collection for builds the answers, taking each record apart.
Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart
What every language printed
[1125, 2915, 515, 420, 700] 200000000000000
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs. Runs on this device: a JavaScript build of this program (about 10 KB), made when the page was built. The first run also downloads the JavaScript runner (about 0.6 MB), which is kept for the next runs. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 155 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device: a .NET build of this program (about 3 KB), made when the page was built. The first run also downloads .NET (about 3.6 MB), which is kept for the next runs. Edit runs your changes in the browser: the first edited run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 12 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device: a WebAssembly build of this program (about 20 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads the JavaScript runner (about 0.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 718 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 1.7 MB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads Ruby (about 10.2 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 182 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 10 KB), made when the page was built. To change the code, copy it and run it with the command below.Your run, in this browser
All 14 print the same five answers, then the total of the largest ledger the limits allow, 200,000 days of 10⁹,
which is 2 × 10¹⁴. The compiled languages keep the prefix totals in 64-bit integers (long in Java and C#,
std::int64_t in C++ and C, i64 in Rust); the section on overflow below shows why. The C++ version builds the list
with std::partial_sum from <numeric>, writing from prefix.begin() + 1 so that prefix[0] stays 0. In Go, the
same loop needs int64 for the totals: the language specification allows int to be 32 or 64 bits wide.
Why it is correct
The loop keeps one fact true, its loop invariant: A statement about a loop's variables that is true before the first pass and after every pass. When the loop stops, it and the exit condition say that the answer is right. More in “Dry runs and loop invariants”: after it has handled day d,
prefix[d + 1] is the total of days 0 to d. It holds at the start, where prefix[0] is the total of no days at
all, 0, and each step adds exactly the next day. So once the loop ends, prefix[i] is the total of the first i
days for every i from 0 to n.
A query then subtracts two such totals. prefix[last + 1] is the total of days 0 to last, and prefix[first] is
the total of days 0 to first − 1. The days before first are in both, so they cancel, and what is left is the
total of days first to last, which is the answer. When first is 0, nothing is taken away, and the formula still
holds.
Key idea
Build the running totals once, with a 0 in front, and every range total is prefix[last + 1] - prefix[first]: the
days before the range are in both entries and cancel.
A dry run
For the first week, prefix is [0, 420, 800, 800, 1315, 1925, 2215, 2915], and each query reads two entries:
- (2, 4):
prefix[5] - prefix[2]= 1,925 − 800 = 1,125 - (0, 6):
prefix[7] - prefix[0]= 2,915 − 0 = 2,915 - (3, 3):
prefix[4] - prefix[3]= 1,315 − 800 = 515 - (0, 0):
prefix[1] - prefix[0]= 420 − 0 = 420 - (6, 6):
prefix[7] - prefix[6]= 2,915 − 2,215 = 700
Day 2 had no sales, so prefix[2] and prefix[3] are equal, and the query (3, 3) returns sales[3] alone. Step
through the same five queries on the list itself:
The drawing shows the whole scene; its 7 steps are listed below.
Every step as text
- The prefix list. These are the eight entries of prefix for the first week. prefix[i] holds the total of the first i days, so prefix[0] is the total of no days at all.
- Days 2 to 4. The query (2, 4) reads prefix[5], the first five days, and takes away prefix[2], the first two: 1,925 − 800 = 1,125.
- Days 0 to 6. The whole week reads prefix[7] and prefix[0]. The 0 in front means that a range starting on day 0 needs no special case: 2,915 − 0 = 2,915.
- Day 3 alone. A single day reads two neighbours: prefix[4] − prefix[3] = 1,315 − 800 = 515, which is sales[3] itself.
- Day 0 alone. The first day reads prefix[1] and the 0 in front: 420 − 0 = 420.
- Day 6 alone. The last day reads the last two entries: prefix[7] − prefix[6] = 2,915 − 2,215 = 700.
- Two reads per query. Five queries read ten entries in all, whatever the lengths of their ranges. Once the list is built, each query costs one subtraction, O(1).
The cost
| Operation | Time | Extra space |
|---|---|---|
| Brute force: add up each range again | O(n × q) | O(1) |
| Prefix sums: build once, then subtract | O(n + q) | O(n): n + 1 numbers |
At the limits, the prefix version does 200,000 additions and 200,000 subtractions instead of up to 4 × 10¹⁰ additions. The price is memory: n + 1 extra numbers, 1.6 MB as 64-bit integers for 200,000 days.
In a live round
Say the plan in two sentences before you code it: “Adding up each range again is O(n × q), up to 4 × 10¹⁰ steps here. The ledger doesn’t change, so I’ll build running totals once with a 0 in front, and each query becomes one subtraction: O(n + q) time and O(n) extra memory.”
Checkpoint
Check: One subtraction per range, and why it is right
Testing: a stress test catches the off-by-one slip
A stress test: A check that runs a fast solution and a trusted brute force on many small random inputs and stops at the first input on which they disagree, which then becomes a test case. More in “From brute force to optimal: the usual moves”, as in the
lesson on brute force to optimal, compares the fast version with the
brute force on many small random ledgers, the shortest first. It also tries a version with a plausible slip,
prefix[last] - prefix[first]:
import random
from brute import range_totals_brute
def range_totals(sales, queries):
"""The prefix-sum version: build the totals once, then one subtraction per query."""
prefix = [0] * (len(sales) + 1)
for day, amount in enumerate(sales):
prefix[day + 1] = prefix[day] + amount
return [prefix[last + 1] - prefix[first] for first, last in queries]
def range_totals_short(sales, queries):
"""A plausible slip: prefix[last] - prefix[first] stops one day early."""
prefix = [0]
for amount in sales:
prefix.append(prefix[-1] + amount)
return [prefix[last] - prefix[first] for first, last in queries]
def first_failure(candidate, cases=1_000, seed=6):
"""Runs candidate and the brute force on small random ledgers, shortest first, until they disagree."""
rng = random.Random(seed)
for case in range(cases):
days = 1 + case * 8 // cases # 1 to 8 days
sales = [rng.randint(0, 9) for _ in range(days)]
queries = []
for _ in range(3):
first = rng.randrange(days)
queries.append((first, rng.randrange(first, days)))
got, expected = candidate(sales, queries), range_totals_brute(sales, queries)
if got != expected:
return f"fails on sales {sales}, queries {queries}: got {got}, expected {expected}"
return f"agrees with the brute force on {cases:,} random ledgers"
print("range_totals: ", first_failure(range_totals))
print("range_totals_short:", first_failure(range_totals_short)) Output
range_totals: agrees with the brute force on 1,000 random ledgers range_totals_short: fails on sales [9], queries [(0, 0), (0, 0), (0, 0)]: got [0, 0, 0], expected [9, 9, 9]
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 stress.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
The correct version agrees on all 1,000 ledgers. The slip fails on the first ledger with a day that sold something:
a single day of 9 and the query (0, 0). It returns 0, because prefix[last] - prefix[first] is the total of days
first to last − 1, which stops one day early, and for a one-day range that leaves no day at all.
Edge cases and common bugs
- A range starting on day 0 needs no special case, thanks to the 0 in front.
- A range of one day,
first == last, returnsprefix[first + 1] - prefix[first], which issales[first]. - Days numbered from 1 in the input: convert each query once, or use
prefix[last] - prefix[first - 1]. Settle this in the clarifying step, before you write the formula. - Negative values, such as refunds, change nothing: prefix sums never needed the numbers to be positive.
- A ledger that changes after the prefix list is built makes every later prefix out of date. Prefix sums suit data that stays the same while the queries run.
- Totals that outgrow their type, the bug that tests with small numbers never catch. It has its own section below.
Variants
The same list answers more than totals:
- Month to date is the range from the first day of the month to today.
- An average over a range is the range total divided by
last - first + 1, the number of days. - A count of days that match a condition is a prefix sum of ones and zeros, one for each day that matches. The exercise below counts days with no sales this way.
- Any operation that can be undone works like addition. XOR is one:
x ^ xis 0, so a range’s XOR isprefix[last + 1] ^ prefix[first]. A minimum or a maximum cannot be undone, so range minimums need a different structure, which a later module builds.
Follow-up questions
Can you answer the queries with O(1) extra memory? Yes, by turning sales itself into running totals
(sales[day] += sales[day - 1] from day 1 on). A range is then sales[last], minus sales[first - 1] when first is
above 0. You lose the original figures, and the special case for day 0 comes back.
The shop adds a new day to the ledger. Do you rebuild everything? No: append prefix[-1] + new_day to the
prefix list. It costs O(1), and the old prefixes stay correct, because a new day only ever comes after them.
Checkpoint
Check: Stress tests, edge cases and variants
Overflow: size the totals from the last prefix
The largest number the prefix list holds is its last entry, the total of the whole ledger: up to
200,000 × 10⁹ = 2 × 10¹⁴. The largest Java int is 2,147,483,647 (section 4.2.1 of the Java Language
Specification), and the specification adds that integer operators give no sign of an
integer overflow: A result too large for its integer type. Java and Go wrap it around silently, signed overflow in C and C++ is undefined behaviour, and Python's integers simply grow. More in “Edge cases and tests before you code” (section 4.2.2) and that an addition never throws an exception
(section 15.18.2). Here is the largest ledger the problem allows, added up into an int[] and into a long[]:
import java.util.Arrays;
public class Overflow {
public static void main(String[] args) {
// The largest ledger the limits allow: 200,000 days of 1,000,000,000 each.
int[] sales = new int[200_000];
Arrays.fill(sales, 1_000_000_000); // one day fits in an int
int[] prefix32 = new int[sales.length + 1];
long[] prefix64 = new long[sales.length + 1];
for (int day = 0; day < sales.length; day++) {
prefix32[day + 1] = prefix32[day] + sales[day];
prefix64[day + 1] = prefix64[day] + sales[day];
}
int last = sales.length - 1;
System.out.println("int prefix, days 0 to " + last + ": " + (prefix32[last + 1] - prefix32[0]));
System.out.println("long prefix, days 0 to " + last + ": " + (prefix64[last + 1] - prefix64[0]));
}
} Output
int prefix, days 0 to 199999: 552894464 long prefix, days 0 to 199999: 200000000000000
Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. To run it yourself: java Overflow.java
The int version prints 552,894,464: the true total minus 46,566 × 2³², a positive number that looks plausible.
The fix is a 64-bit type for the prefix list and the answers: a Java long, a C++
long long (or std::int64_t), a Go int64. Java can keep each day’s sales in an int, as Overflow.java does,
because each day fits and Java widens it when it is added to a long. The C++ version above stores the sales as
std::int64_t as well, so that std::partial_sum adds in 64 bits. In JavaScript every whole number up to
2⁵³ − 1, about 9 × 10¹⁵, is exact, so 2 × 10¹⁴ is safe, and the JavaScript tab above prints it exactly. Python’s
integers have unlimited precision. The lesson on edge cases compares
how each of five languages behaves when a sum overflows.
Ledgers kept in paise
Amounts are often stored in paise, as whole numbers, to avoid rounding errors. A 32-bit int holds at most
2,147,483,647 paise, which is ₹2,14,74,836.47, a little over ₹2.14 crore. A shop that takes ₹10 lakh a day passes
that in 22 days, so a month-to-date total in paise needs a 64-bit integer.
The prefix list and its type, language by language
How each language builds the prefix list, and the type its totals need:
- Python:
accumulate(sales, initial=0)or a loop; aninthas no upper limit. - JavaScript: a loop; a
numberis exact up to 2⁵³ − 1, andBigIntgoes beyond it. - Java: a loop, or
Arrays.parallelPrefix; totals inlong. - C++:
std::partial_sum;long longfor the totals and for the sales. - Go: a loop; totals in
int64.
Two library calls need a word of care. Arrays.parallelPrefix(a, Long::sum) turns a Java array into its own running
totals, in place, so the result has no 0 in front. std::partial_sum writes wherever its third argument points,
which is why the C++ version above passes prefix.begin() + 1 and leaves prefix[0] at 0.
Checkpoint
Check: A type large enough for the last prefix
Prefix sums in disguise: the balance day
Prefix sums often appear in problems that never say “range”. Take this one: find the first day on which the sales of all the days before it equal the sales of all the days after it, the day itself counting on neither side, or return −1 if there is no such day.
The brute force adds up both sides again for every day, which is O(n²). Now notice what the two sides are. The days
before day d total prefix[d], and the days after it total the whole ledger minus prefix[d] minus sales[d]. So
one running total of the days so far, together with the total of the whole ledger, checks each day in O(1). Step
through it on the first ledger below:
The drawing shows the whole scene; its 5 steps are listed below.
Every step as text
- One sum first. The ledger is [3, 8, 2, 6, 5]. One pass adds the whole ledger, 24, and before starts at 0, the total of the days before day 0.
- Day 0. Day 0 sold 3. The days after it total 24 − 0 − 3 = 21, and the days before it total 0, so day 0 does not balance.
- Day 1. before has grown to 3. Day 1 sold 8, so the days after it total 24 − 3 − 8 = 13, against 3 before it.
- Day 2 balances. before is now 3 + 8 = 11. Day 2 sold 2, and the days after it total 24 − 11 − 2 = 11. Both sides are 11, so the answer is day 2.
- Each day costs O(1). Every day needed one comparison and one addition to before, never a new sum of the days after it. That is the prefix-sum idea with a single running total.
The same check in 14 languages, with the brute force beside it, on five ledgers and on every ledger of one to five days whose daily sales run from −2 to 2:
Python 3.14 · main.py
def balance_day_brute(sales: list[int]) -> int:
# Adds up both sides again for every day.
for day in range(len(sales)):
if sum(sales[:day]) == sum(sales[day + 1 :]):
return day
return -1
def balance_day(sales: list[int]) -> int:
# The days after day d total the whole ledger minus the days before d minus day d.
whole = sum(sales)
before = 0
for day, amount in enumerate(sales):
if before == whole - before - amount:
return day
before += amount
return -1
for sales in ([3, 8, 2, 6, 5], [4, -1, 9, 3], [0, 6, -6], [5, 5], [7]):
print(sales, balance_day_brute(sales), balance_day(sales))
# Every ledger of 1 to 5 days with daily sales from -2 to 2.
tried = agree = 0
for days in range(1, 6):
for code in range(5**days):
ledger = [code // 5**i % 5 - 2 for i in range(days)]
tried += 1
agree += balance_day(ledger) == balance_day_brute(ledger)
print(f"same answer on {agree} of {tried} ledgers of 1 to 5 days") In Python: sum(sales[:day]) copies that part of the list before it adds it up; enumerate gives each day with its sales.
Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py
JavaScript Node 24 · main.mjs
const total = (values) => values.reduce((sum, value) => sum + value, 0);
function balanceDayBrute(sales) {
// Adds up both sides again for every day.
for (let day = 0; day < sales.length; day++) {
if (total(sales.slice(0, day)) === total(sales.slice(day + 1))) {
return day;
}
}
return -1;
}
function balanceDay(sales) {
// The days after day d total the whole ledger minus the days before d minus day d.
const whole = total(sales);
let before = 0;
for (const [day, amount] of sales.entries()) {
if (before === whole - before - amount) {
return day;
}
before += amount;
}
return -1;
}
for (const sales of [[3, 8, 2, 6, 5], [4, -1, 9, 3], [0, 6, -6], [5, 5], [7]]) {
console.log(`[${sales.join(", ")}] ${balanceDayBrute(sales)} ${balanceDay(sales)}`);
}
// Every ledger of 1 to 5 days with daily sales from -2 to 2.
let tried = 0;
let agree = 0;
let codes = 1;
for (let days = 1; days <= 5; days++) {
codes *= 5;
for (let code = 0; code < codes; code++) {
const ledger = [];
let rest = code;
for (let i = 0; i < days; i++) {
ledger.push((rest % 5) - 2);
rest = Math.trunc(rest / 5);
}
tried++;
if (balanceDay(ledger) === balanceDayBrute(ledger)) {
agree++;
}
}
}
console.log(`same answer on ${agree} of ${tried} ledgers of 1 to 5 days`); In JavaScript: entries() gives each position with its value, so the loop needs no index arithmetic; slice copies, as in Python.
Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs
Java 25 LTS · Main.java
import java.util.Arrays;
public class Main {
static int balanceDayBrute(int[] sales) {
// Adds up both sides again for every day.
for (int day = 0; day < sales.length; day++) {
int left = Arrays.stream(sales, 0, day).sum();
int right = Arrays.stream(sales, day + 1, sales.length).sum();
if (left == right) {
return day;
}
}
return -1;
}
static int balanceDay(int[] sales) {
// The days after day d total the whole ledger minus the days before d minus day d.
int whole = Arrays.stream(sales).sum();
int before = 0;
for (int day = 0; day < sales.length; day++) {
if (before == whole - before - sales[day]) {
return day;
}
before += sales[day];
}
return -1;
}
public static void main(String[] args) {
int[][] ledgers = {{3, 8, 2, 6, 5}, {4, -1, 9, 3}, {0, 6, -6}, {5, 5}, {7}};
for (int[] sales : ledgers) {
System.out.println(
Arrays.toString(sales) + " " + balanceDayBrute(sales) + " " + balanceDay(sales));
}
// Every ledger of 1 to 5 days with daily sales from -2 to 2.
int tried = 0;
int agree = 0;
int codes = 1;
for (int days = 1; days <= 5; days++) {
codes *= 5;
for (int code = 0; code < codes; code++) {
int[] ledger = new int[days];
int rest = code;
for (int i = 0; i < days; i++) {
ledger[i] = rest % 5 - 2;
rest /= 5;
}
tried++;
if (balanceDay(ledger) == balanceDayBrute(ledger)) {
agree++;
}
}
}
System.out.println("same answer on " + agree + " of " + tried + " ledgers of 1 to 5 days");
}
} In Java: Arrays.stream(sales, from, to).sum() adds a part of the array without copying it, and Arrays.toString prints the ledger in brackets.
Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java
C++23 · main.cpp
#include <numeric>
#include <print>
#include <vector>
int balance_day_brute(const std::vector<int> &sales) {
// Adds up both sides again for every day.
for (std::size_t day = 0; day < sales.size(); ++day) {
const int left = std::accumulate(sales.begin(), sales.begin() + day, 0);
const int right = std::accumulate(sales.begin() + day + 1, sales.end(), 0);
if (left == right) {
return static_cast<int>(day);
}
}
return -1;
}
int balance_day(const std::vector<int> &sales) {
// The days after day d total the whole ledger minus the days before d minus
// day d.
const int whole = std::accumulate(sales.begin(), sales.end(), 0);
int before = 0;
for (std::size_t day = 0; day < sales.size(); ++day) {
if (before == whole - before - sales[day]) {
return static_cast<int>(day);
}
before += sales[day];
}
return -1;
}
int main() {
const std::vector<std::vector<int>> ledgers = {
{3, 8, 2, 6, 5}, {4, -1, 9, 3}, {0, 6, -6}, {5, 5}, {7}};
for (const auto &sales : ledgers) {
std::println("{} {} {}", sales, balance_day_brute(sales),
balance_day(sales));
}
// Every ledger of 1 to 5 days with daily sales from -2 to 2.
int tried = 0;
int agree = 0;
int codes = 1;
for (int days = 1; days <= 5; ++days) {
codes *= 5;
for (int code = 0; code < codes; ++code) {
std::vector<int> ledger;
int rest = code;
for (int i = 0; i < days; ++i) {
ledger.push_back(rest % 5 - 2);
rest /= 5;
}
++tried;
if (balance_day(ledger) == balance_day_brute(ledger)) {
++agree;
}
}
}
std::println("same answer on {} of {} ledgers of 1 to 5 days", agree, tried);
} In C++: std::accumulate adds a range given by two iterators, so the brute force needs no copies; std::println prints a vector in brackets, new in C++23.
Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main
C# 14 · .NET 10 · app.cs
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
int[][] ledgers = [[3, 8, 2, 6, 5], [4, -1, 9, 3], [0, 6, -6], [5, 5], [7]];
foreach (var sales in ledgers)
{
Console.WriteLine($"[{string.Join(", ", sales)}] {BalanceDayBrute(sales)} {BalanceDay(sales)}");
}
// Every ledger of 1 to 5 days with daily sales from -2 to 2.
int tried = 0;
int agree = 0;
int codes = 1;
for (int days = 1; days <= 5; days++)
{
codes *= 5;
for (int code = 0; code < codes; code++)
{
var ledger = new int[days];
int rest = code;
for (int i = 0; i < days; i++)
{
ledger[i] = rest % 5 - 2;
rest /= 5;
}
tried++;
if (BalanceDay(ledger) == BalanceDayBrute(ledger))
{
agree++;
}
}
}
Console.WriteLine($"same answer on {agree} of {tried} ledgers of 1 to 5 days");
static int BalanceDayBrute(int[] sales)
{
// Adds up both sides again for every day.
for (int day = 0; day < sales.Length; day++)
{
if (sales[..day].Sum() == sales[(day + 1)..].Sum())
{
return day;
}
}
return -1;
}
static int BalanceDay(int[] sales)
{
// The days after day d total the whole ledger minus the days before d minus day d.
int whole = sales.Sum();
int before = 0;
for (int day = 0; day < sales.Length; day++)
{
if (before == whole - before - sales[day])
{
return day;
}
before += sales[day];
}
return -1;
} In C#: sales[..day] and sales[(day + 1)..] are ranges that copy part of the array, and Sum() from LINQ adds them.
Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs
C23 · main.c
#include <stddef.h>
#include <stdio.h>
static int sum(const int *values, size_t count) {
int total = 0;
for (size_t i = 0; i < count; i++) {
total += values[i];
}
return total;
}
static int balance_day_brute(const int *sales, size_t days) {
// Adds up both sides again for every day.
for (size_t day = 0; day < days; day++) {
if (sum(sales, day) == sum(sales + day + 1, days - day - 1)) {
return (int)day;
}
}
return -1;
}
static int balance_day(const int *sales, size_t days) {
// The days after day d total the whole ledger minus the days before d minus
// day d.
const int whole = sum(sales, days);
int before = 0;
for (size_t day = 0; day < days; day++) {
if (before == whole - before - sales[day]) {
return (int)day;
}
before += sales[day];
}
return -1;
}
static void print_ledger(const int *sales, size_t days) {
printf("[");
for (size_t i = 0; i < days; i++) {
printf("%s%d", i == 0 ? "" : ", ", sales[i]);
}
printf("]");
}
int main(void) {
static const int a[] = {3, 8, 2, 6, 5}, b[] = {4, -1, 9, 3}, c[] = {0, 6, -6},
d[] = {5, 5}, e[] = {7};
const struct {
const int *sales;
size_t days;
} ledgers[] = {{a, 5}, {b, 4}, {c, 3}, {d, 2}, {e, 1}};
for (size_t i = 0; i < sizeof ledgers / sizeof ledgers[0]; i++) {
print_ledger(ledgers[i].sales, ledgers[i].days);
printf(" %d %d\n", balance_day_brute(ledgers[i].sales, ledgers[i].days),
balance_day(ledgers[i].sales, ledgers[i].days));
}
// Every ledger of 1 to 5 days with daily sales from -2 to 2.
int tried = 0;
int agree = 0;
int codes = 1;
int ledger[5];
for (size_t days = 1; days <= 5; days++) {
codes *= 5;
for (int code = 0; code < codes; code++) {
int rest = code;
for (size_t i = 0; i < days; i++) {
ledger[i] = rest % 5 - 2;
rest /= 5;
}
tried++;
if (balance_day(ledger, days) == balance_day_brute(ledger, days)) {
agree++;
}
}
}
printf("same answer on %d of %d ledgers of 1 to 5 days\n", agree, tried);
return 0;
} In C: sum takes a pointer and a count, so sales + day + 1 is the part after the day without a copy; the ledgers are a small array of pointers and lengths.
Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main
PHP 8.5 · main.php
<?php
declare(strict_types=1);
/** @param list<int> $sales */
function balanceDayBrute(array $sales): int
{
// Adds up both sides again for every day.
foreach (array_keys($sales) as $day) {
if (array_sum(array_slice($sales, 0, $day)) === array_sum(array_slice($sales, $day + 1))) {
return $day;
}
}
return -1;
}
/** @param list<int> $sales */
function balanceDay(array $sales): int
{
// The days after day d total the whole ledger minus the days before d minus day d.
$whole = array_sum($sales);
$before = 0;
foreach ($sales as $day => $amount) {
if ($before === $whole - $before - $amount) {
return $day;
}
$before += $amount;
}
return -1;
}
foreach ([[3, 8, 2, 6, 5], [4, -1, 9, 3], [0, 6, -6], [5, 5], [7]] as $sales) {
printf("[%s] %d %d\n", implode(', ', $sales), balanceDayBrute($sales), balanceDay($sales));
}
// Every ledger of 1 to 5 days with daily sales from -2 to 2.
$tried = 0;
$agree = 0;
$codes = 1;
for ($days = 1; $days <= 5; $days++) {
$codes *= 5;
for ($code = 0; $code < $codes; $code++) {
$ledger = [];
$rest = $code;
for ($i = 0; $i < $days; $i++) {
$ledger[] = $rest % 5 - 2;
$rest = intdiv($rest, 5);
}
$tried++;
if (balanceDay($ledger) === balanceDayBrute($ledger)) {
$agree++;
}
}
}
echo "same answer on {$agree} of {$tried} ledgers of 1 to 5 days\n"; In PHP: array_slice copies part of the list and array_sum adds it; intdiv keeps the base-5 digits whole numbers.
Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. It runs in your browser with php-wasm 0.2.0 (PHP 8.5.2). To run it yourself: php main.php
Rust 1.99 · main.rs
fn balance_day_brute(sales: &[i32]) -> Option<usize> {
// Adds up both sides again for every day.
(0..sales.len()).find(|&day| sales[..day].iter().sum::<i32>() == sales[day + 1..].iter().sum())
}
fn balance_day(sales: &[i32]) -> Option<usize> {
// The days after day d total the whole ledger minus the days before d minus day d.
let whole: i32 = sales.iter().sum();
let mut before = 0;
for (day, &amount) in sales.iter().enumerate() {
if before == whole - before - amount {
return Some(day);
}
before += amount;
}
None
}
fn shown(day: Option<usize>) -> String {
day.map_or("-1".to_string(), |d| d.to_string())
}
fn main() {
let ledgers: [&[i32]; 5] = [&[3, 8, 2, 6, 5], &[4, -1, 9, 3], &[0, 6, -6], &[5, 5], &[7]];
for sales in ledgers {
let (brute, fast) = (balance_day_brute(sales), balance_day(sales));
println!("{sales:?} {} {}", shown(brute), shown(fast));
}
// Every ledger of 1 to 5 days with daily sales from -2 to 2.
let (mut tried, mut agree) = (0, 0);
for days in 1..=5u32 {
for code in 0..5_i32.pow(days) {
let ledger: Vec<i32> = (0..days).map(|i| code / 5_i32.pow(i) % 5 - 2).collect();
tried += 1;
if balance_day(&ledger) == balance_day_brute(&ledger) {
agree += 1;
}
}
}
println!("same answer on {agree} of {tried} ledgers of 1 to 5 days");
} In Rust: The functions return Option<usize>, None for no balance day, and shown prints it as -1; sales[..day] borrows a part of the slice without copying.
Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main
TypeScript 6.0 · main.ts
const total = (values: number[]): number => values.reduce((sum, value) => sum + value, 0);
function balanceDayBrute(sales: number[]): number {
// Adds up both sides again for every day.
for (let day = 0; day < sales.length; day++) {
if (total(sales.slice(0, day)) === total(sales.slice(day + 1))) {
return day;
}
}
return -1;
}
function balanceDay(sales: number[]): number {
// The days after day d total the whole ledger minus the days before d minus day d.
const whole = total(sales);
let before = 0;
for (const [day, amount] of sales.entries()) {
if (before === whole - before - amount) {
return day;
}
before += amount;
}
return -1;
}
const ledgers: number[][] = [[3, 8, 2, 6, 5], [4, -1, 9, 3], [0, 6, -6], [5, 5], [7]];
for (const sales of ledgers) {
console.log(`[${sales.join(", ")}] ${balanceDayBrute(sales)} ${balanceDay(sales)}`);
}
// Every ledger of 1 to 5 days with daily sales from -2 to 2.
let tried = 0;
let agree = 0;
let codes = 1;
for (let days = 1; days <= 5; days++) {
codes *= 5;
for (let code = 0; code < codes; code++) {
const ledger: number[] = [];
let rest = code;
for (let i = 0; i < days; i++) {
ledger.push((rest % 5) - 2);
rest = Math.trunc(rest / 5);
}
tried++;
if (balanceDay(ledger) === balanceDayBrute(ledger)) {
agree++;
}
}
}
console.log(`same answer on ${agree} of ${tried} ledgers of 1 to 5 days`); In TypeScript: The ledgers are typed number[][], so tsc checks every call; the program is otherwise the JavaScript one.
Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts
Go 1.27 · main.go
package main
import (
"fmt"
"strconv"
"strings"
)
func sum(values []int) int {
total := 0
for _, v := range values {
total += v
}
return total
}
func balanceDayBrute(sales []int) int {
// Adds up both sides again for every day.
for day := range sales {
if sum(sales[:day]) == sum(sales[day+1:]) {
return day
}
}
return -1
}
func balanceDay(sales []int) int {
// The days after day d total the whole ledger minus the days before d minus day d.
whole := sum(sales)
before := 0
for day, amount := range sales {
if before == whole-before-amount {
return day
}
before += amount
}
return -1
}
func shown(sales []int) string {
parts := make([]string, len(sales))
for i, v := range sales {
parts[i] = strconv.Itoa(v)
}
return "[" + strings.Join(parts, ", ") + "]"
}
func main() {
ledgers := [][]int{{3, 8, 2, 6, 5}, {4, -1, 9, 3}, {0, 6, -6}, {5, 5}, {7}}
for _, sales := range ledgers {
fmt.Println(shown(sales), balanceDayBrute(sales), balanceDay(sales))
}
// Every ledger of 1 to 5 days with daily sales from -2 to 2.
tried, agree, codes := 0, 0, 1
for days := 1; days <= 5; days++ {
codes *= 5
for code := range codes {
ledger := make([]int, days)
rest := code
for i := range ledger {
ledger[i] = rest%5 - 2
rest /= 5
}
tried++
if balanceDay(ledger) == balanceDayBrute(ledger) {
agree++
}
}
}
fmt.Printf("same answer on %d of %d ledgers of 1 to 5 days\n", agree, tried)
} In Go: sales[:day] is a slice of the same array, not a copy, and a range over an integer, for code := range codes, counts from 0 to codes − 1.
Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go
Swift 6.4 · main.swift
func balanceDayBrute(_ sales: [Int]) -> Int {
// Adds up both sides again for every day.
for day in sales.indices where sales[..<day].reduce(0, +) == sales[(day + 1)...].reduce(0, +) {
return day
}
return -1
}
func balanceDay(_ sales: [Int]) -> Int {
// The days after day d total the whole ledger minus the days before d minus day d.
let whole = sales.reduce(0, +)
var before = 0
for (day, amount) in sales.enumerated() {
if before == whole - before - amount {
return day
}
before += amount
}
return -1
}
for sales in [[3, 8, 2, 6, 5], [4, -1, 9, 3], [0, 6, -6], [5, 5], [7]] {
print(sales, balanceDayBrute(sales), balanceDay(sales))
}
// Every ledger of 1 to 5 days with daily sales from -2 to 2.
var tried = 0
var agree = 0
var codes = 1
for days in 1...5 {
codes *= 5
for code in 0..<codes {
var ledger: [Int] = []
var rest = code
for _ in 0..<days {
ledger.append(rest % 5 - 2)
rest /= 5
}
tried += 1
if balanceDay(ledger) == balanceDayBrute(ledger) {
agree += 1
}
}
}
print("same answer on \(agree) of \(tried) ledgers of 1 to 5 days") In Swift: sales[..<day] is an ArraySlice that shares the array's storage, and reduce(0, +) adds it; the where clause filters the days of the loop.
Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main
Ruby 4.0 · main.rb
# frozen_string_literal: true
def balance_day_brute(sales)
# Adds up both sides again for every day.
sales.each_index.find { |day| sales[0...day].sum == sales[(day + 1)..].sum } || -1
end
def balance_day(sales)
# The days after day d total the whole ledger minus the days before d minus day d.
whole = sales.sum
before = 0
sales.each_with_index do |amount, day|
return day if before == whole - before - amount
before += amount
end
-1
end
[[3, 8, 2, 6, 5], [4, -1, 9, 3], [0, 6, -6], [5, 5], [7]].each do |sales|
puts "#{sales.inspect} #{balance_day_brute(sales)} #{balance_day(sales)}"
end
# Every ledger of 1 to 5 days with daily sales from -2 to 2.
tried = 0
agree = 0
(1..5).each do |days|
(5**days).times do |code|
ledger = Array.new(days) { |i| (code / (5**i) % 5) - 2 }
tried += 1
agree += 1 if balance_day(ledger) == balance_day_brute(ledger)
end
end
puts "same answer on #{agree} of #{tried} ledgers of 1 to 5 days" In Ruby: each_index.find returns nil when no day balances, so || -1 turns it into the answer; inspect prints the ledger in brackets.
Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb
Kotlin 2.4 · Main.kt
fun balanceDayBrute(sales: IntArray): Int {
// Adds up both sides again for every day.
for (day in sales.indices) {
if (sales.take(day).sum() == sales.drop(day + 1).sum()) {
return day
}
}
return -1
}
fun balanceDay(sales: IntArray): Int {
// The days after day d total the whole ledger minus the days before d minus day d.
val whole = sales.sum()
var before = 0
for ((day, amount) in sales.withIndex()) {
if (before == whole - before - amount) {
return day
}
before += amount
}
return -1
}
fun main() {
val ledgers =
listOf(
intArrayOf(3, 8, 2, 6, 5),
intArrayOf(4, -1, 9, 3),
intArrayOf(0, 6, -6),
intArrayOf(5, 5),
intArrayOf(7),
)
for (sales in ledgers) {
println("${sales.contentToString()} ${balanceDayBrute(sales)} ${balanceDay(sales)}")
}
// Every ledger of 1 to 5 days with daily sales from -2 to 2.
var tried = 0
var agree = 0
var codes = 1
for (days in 1..5) {
codes *= 5
for (code in 0 until codes) {
var rest = code
val ledger =
IntArray(days) {
val value = rest % 5 - 2
rest /= 5
value
}
tried++
if (balanceDay(ledger) == balanceDayBrute(ledger)) {
agree++
}
}
}
println("same answer on $agree of $tried ledgers of 1 to 5 days")
} In Kotlin: take and drop copy part of the array into a list; withIndex gives each day with its sales.
Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar
Dart 3.13 · main.dart
int total(Iterable<int> values) => values.fold(0, (sum, value) => sum + value);
int balanceDayBrute(List<int> sales) {
// Adds up both sides again for every day.
for (var day = 0; day < sales.length; day++) {
if (total(sales.take(day)) == total(sales.skip(day + 1))) {
return day;
}
}
return -1;
}
int balanceDay(List<int> sales) {
// The days after day d total the whole ledger minus the days before d minus day d.
final whole = total(sales);
var before = 0;
for (final (day, amount) in sales.indexed) {
if (before == whole - before - amount) {
return day;
}
before += amount;
}
return -1;
}
void main() {
final ledgers = [
[3, 8, 2, 6, 5],
[4, -1, 9, 3],
[0, 6, -6],
[5, 5],
[7],
];
for (final sales in ledgers) {
print('$sales ${balanceDayBrute(sales)} ${balanceDay(sales)}');
}
// Every ledger of 1 to 5 days with daily sales from -2 to 2.
var tried = 0;
var agree = 0;
var codes = 1;
for (var days = 1; days <= 5; days++) {
codes *= 5;
for (var code = 0; code < codes; code++) {
final ledger = <int>[];
var rest = code;
for (var i = 0; i < days; i++) {
ledger.add(rest % 5 - 2);
rest ~/= 5;
}
tried++;
if (balanceDay(ledger) == balanceDayBrute(ledger)) {
agree++;
}
}
}
print('same answer on $agree of $tried ledgers of 1 to 5 days');
} In Dart: take and skip are lazy views of the list, so the brute force copies nothing; indexed gives each day with its sales as a record.
Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart
What every language printed
[3, 8, 2, 6, 5] 2 2 [4, -1, 9, 3] 2 2 [0, 6, -6] 0 0 [5, 5] -1 -1 [7] 0 0 same answer on 3905 of 3905 ledgers of 1 to 5 days
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs. Runs on this device: a JavaScript build of this program (about 10 KB), made when the page was built. The first run also downloads the JavaScript runner (about 0.6 MB), which is kept for the next runs. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 156 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device: a .NET build of this program (about 3 KB), made when the page was built. The first run also downloads .NET (about 3.6 MB), which is kept for the next runs. Edit runs your changes in the browser: the first edited run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 9 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads PHP (about 4.3 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 21 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads the JavaScript runner (about 0.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 719 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 1.7 MB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads Ruby (about 10.2 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 181 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 11 KB), made when the page was built. To change the code, copy it and run it with the command below.Your run, in this browser
Both versions agree on the five ledgers and on all 3,905 short ledgers. The cases worth saying aloud in a round: the
first day can balance, because the side before it is empty and totals 0 ([0, 6, -6]); a ledger of one day balances
on that day; negative values are fine ([4, -1, 9, 3]); and a ledger with no balance day returns −1 ([5, 5]). This
version keeps a single running total instead of a list, because it reads the prefixes in order and never needs one
twice.
The signal is a condition that compares what comes before a position with what comes after it: “left and right”, “before and after”, “every way to split”. Running totals from the left, and the whole total, usually make each check O(1).
Checkpoint
Check: Before-and-after conditions as prefix sums
Practise: totals and quiet days for many ranges
The exercise asks for two numbers for every range, the total and the days with no sales. Its sample tests run on this page, and the last one gives your function 20,000 days and 20,000 queries:
Exercise · Easy · Python
Totals and quiet days for many ranges
The shop's accounts page now shows two numbers for every range of days: the total sales, and the number of quiet days, the days in the range on which nothing was sold. Write range_report(sales, queries) in report.py.
sales[i]is what the shop took on dayi, a whole number from 0 to 10⁹.- Each query is a pair
(first, last)with0 <= first <= last < len(sales): the daysfirsttolast, both included. - Return a list with one pair
(total, quiet_days)for each query, in the order of the queries.
range_report([420, 0, 515, 0, 0, 290], [(0, 2), (1, 4), (5, 5)])
# [(935, 1), (515, 3), (290, 0)]
There can be up to 200,000 days and 200,000 queries, so adding up each range again is too slow. The sample tests check the example, single days, the whole ledger, a ledger of quiet days only and the largest values. The last test gives your function 20,000 days and 20,000 queries, counts how many values it reads from sales, and stops it once it has read more than four times the number of days.
Starter code · report.py
def range_report(sales, queries):
"""For each query (first, last): the total sales of those days and how many of them had no sales."""
# Replace this line with your code.
return [] The sample tests · test_report.py
import random
from report import range_report
def trusted(sales, queries):
"""Answers the tests trust: add up each range again, and count its zeros."""
return [(sum(sales[first:last + 1]), sales[first:last + 1].count(0)) for first, last in queries]
def as_pairs(result):
"""Accept tuples or lists for the pairs."""
return [tuple(pair) for pair in result]
class Ledger(list):
"""A list of sales that counts the values read from it, and stops a solution that reads too many."""
def __init__(self, values, limit):
super().__init__(values)
self.reads = 0
self.limit = limit
def _read(self, count):
self.reads += count
if self.reads > self.limit:
raise AssertionError(
f"too slow: more than {self.limit:,} values were read from a ledger of {len(self):,} days; "
"build the prefix lists once and answer each query without reading the ledger again"
)
def __getitem__(self, index):
self._read(len(range(*index.indices(len(self)))) if isinstance(index, slice) else 1)
return super().__getitem__(index)
def __iter__(self):
for day in range(len(self)):
self._read(1)
yield super().__getitem__(day)
def test_prompt_example():
"""the example from the prompt"""
assert as_pairs(range_report([420, 0, 515, 0, 0, 290], [(0, 2), (1, 4), (5, 5)])) == [(935, 1), (515, 3), (290, 0)]
def test_single_days():
"""ranges of one day, first == last, quiet and not"""
sales = [7, 0, 12]
assert as_pairs(range_report(sales, [(0, 0), (1, 1), (2, 2)])) == [(7, 0), (0, 1), (12, 0)]
def test_whole_ledger():
"""a range from the first day to the last"""
sales = [5, 0, 9, 0, 3]
assert as_pairs(range_report(sales, [(0, 4)])) == [(17, 2)]
def test_only_quiet_days():
"""a ledger in which nothing was sold"""
assert as_pairs(range_report([0, 0, 0, 0], [(0, 3), (1, 2), (3, 3)])) == [(0, 4), (0, 2), (0, 1)]
def test_largest_values():
"""200,000 days of 10^9, with one quiet day: totals far above 2^31"""
sales = [1_000_000_000] * 200_000
sales[150_000] = 0
queries = [(0, 199_999), (100_000, 199_999), (150_000, 150_000)]
assert as_pairs(range_report(sales, queries)) == [(199_999_000_000_000, 1), (99_999_000_000_000, 1), (0, 1)]
def test_random_small_ledgers():
"""300 random ledgers of up to 10 days, against answers the tests trust"""
rng = random.Random(8)
for _ in range(300):
days = rng.randint(1, 10)
sales = [rng.choice([0, 0, 1, 5, 40]) for _ in range(days)]
queries = []
for _ in range(4):
first = rng.randrange(days)
queries.append((first, rng.randrange(first, days)))
assert as_pairs(range_report(sales, queries)) == trusted(sales, queries), f"range_report({sales}, {queries})"
def test_many_long_queries():
"""20,000 days and 20,000 long queries, reading at most four values per day"""
rng = random.Random(3)
days = 20_000
values = [rng.choice([0, rng.randint(1, 1_000_000_000)]) for _ in range(days)]
queries = [(rng.randrange(10), rng.randrange(days - 10, days)) for _ in range(20_000)]
prefix, quiet = [0], [0]
for amount in values:
prefix.append(prefix[-1] + amount)
quiet.append(quiet[-1] + (amount == 0))
expected = [(prefix[last + 1] - prefix[first], quiet[last + 1] - quiet[first]) for first, last in queries]
assert as_pairs(range_report(Ledger(values, limit=4 * days), queries)) == expected A hint
A quiet day is a day whose sales are 0. Count it as 1 and every other day as 0: the number of quiet days in a range is then the total of those ones and zeros over the range. One pass over sales can build two prefix lists with a 0 in front, one of the sales and one of the quiet days.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.
Sixteen questions cover all six sections. Each answer picks the next question: a slip brings an easier one on the same idea, a right answer a harder one:
Practice that adapts to you
Practise this lesson
16 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
What is a prefix sum array, and how does it give the total of a range in O(1)? It is the list of running totals
of an array, with a 0 in front: prefix[0] = 0 and prefix[i + 1] = prefix[i] + a[i], so prefix[i] is the total
of the first i items. Building it takes one pass, O(n) time and n + 1 numbers of memory. The total of a[first]
to a[last] is prefix[last + 1] - prefix[first]: both prefixes contain the items before first, so they cancel,
and exactly the range is left. That is one subtraction, whatever the length of the range. It fits an array that does
not change and is asked many range totals: for q queries over n items it turns O(n × q) into O(n + q).
Why do many prefix-sum solutions put a 0 at the start, so that the array has n + 1 entries? With the 0,
prefix[i] is the total of the first i items, and every range has the same formula,
prefix[last + 1] - prefix[first], including ranges that start at item 0, where nothing is taken away. Without it,
the array holds the totals of items 0 to i, and a range starting at 0 needs a special case, because the formula
would read the entry before index 0. In Python that mistake does not even fail: index −1 is the last entry, so the
answer is silently wrong. The extra entry costs one number of memory and removes a whole family of
off-by-one error: A bug in which a loop or an index goes one step too far or stops one step short, such as range(len(values) - 1) where every position must be read. More in “Dry runs and loop invariants”.
A round rarely stops at the definition. Three follow-ups often come next: for each, pick one of four answers, and the reply says what that answer gets right or misses:
Checkpoint
Interview round: three follow-up questions
Two more questions go further: what to do when late refunds change past days, and why an int prefix array gives
wrong answers on only some large tests. Each links to its first step and follow-ups:
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Mid to senior
A dashboard answers "total sales from day first to day last" over five years of daily figures, about a million queries a day, from a prefix array. Late refunds now change past days about 5,000 times a day. Do you keep the prefix array? Decide with numbers, then redo the decision for figures kept per minute.
-
Fresher to mid
Your Java solution keeps the prefix totals of a sales ledger in an int[]. It passes most tests on the judge, including some with very large daily figures, but gives wrong answers on a few large tests. Explain exactly which queries come out wrong and why, then fix it.
Key takeaways
- A prefix list holds running totals with a 0 in front, and its invariant, “
prefix[i]is the total of the firstiitems”, is the whole proof: the shared prefix cancels. - The total of items
firsttolastisprefix[last + 1] - prefix[first]: O(n) to build, then O(1) per query. - The cue is many range totals or counts over data that does not change while the queries run.
- Check the fast version against the brute force with a stress test; an off-by-one slip fails on the smallest input.
- Size the type from the largest prefix: 2 × 10⁵ days of 10⁹ need 64-bit totals in Java, C++ and Go.
- Conditions that compare what comes before a position with what comes after it are prefix sums in disguise.
Terms in this lesson
- prefix sum array
- The running totals of a list with a 0 in front: prefix[0] = 0 and prefix[i + 1] = prefix[i] + a[i], so prefix[i] is the total of the first i items and any range total is one subtraction.
- range query
- A question about a contiguous stretch of a list, such as the total or the count of the items from position first to position last, both included.
References
- itertools.accumulate() (The Python Standard Library) (Python Software Foundation)
- Numeric types: int, float, complex (The Python Standard Library) (Python Software Foundation)
- The Java Language Specification, Java SE 25: 4.2.1 Integral Types and Values, 4.2.2 Integer Operations (Oracle)
- The Java Language Specification, Java SE 25: 15.18.2 Additive Operators for Numeric Types (Oracle)
- Java SE 25 API: java.util.Arrays (parallelPrefix) (Oracle)
- Working Draft, Programming Languages: C++ (N4950), [partial.sum] Partial sum (ISO/IEC JTC1/SC22/WG21)
- ECMAScript 2026 Language Specification: Number.MAX_SAFE_INTEGER (Ecma International)
- The Go Programming Language Specification: Numeric types (The Go Authors)
- Integral numeric types (C# reference) (Microsoft)
- Numbers (Kotlin documentation) (JetBrains)
- The Swift Programming Language: The Basics (Int) (Swift.org)
- PHP manual: integers (The PHP Group)
- Numbers in Dart (Dart (Google))
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress