AlgoTales · Roadmap

Square-root decomposition

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

Where you will meet this in real life

Square-root decomposition cuts a long list into blocks of roughly equal size and keeps a summary for each block. A question over a range uses block summaries for the full blocks and looks item by item only at the two loose ends.

Practical use cases

  • Web app: Live totals with frequent edits. A sales dashboard shows the total for any selected range of days while new corrections are entered all day. Recomputing the sum each time scans thousands of rows. Keeping one subtotal per block of 100 days means a range total adds a handful of subtotals and a few loose days. The page stays smooth even when staff keep fixing entries, because each edit only refreshes one small block.
  • Web app: Paginated range counts. A product table counts how many items in a range of positions are marked "in stock", while stock flags toggle often. Each block remembers its own count, so toggling one item updates just one block, and range counts stay quick even with thousands of toggles.
  • Web app: Batch storage pages. A database stores records in pages of about 100 and keeps a small summary in each page header, such as the highest price on the page. A query can then skip every page that cannot match, without opening each record, so most records are never touched.
  • System: Database and storage design. Disk pages and chunked storage engines use the same idea: keep a small summary per chunk so most of the data need not be touched. That is what lets large tables answer questions quickly without reading everything.

The story: Sticky Notes on the Shelf

Raju kept a diary: cups of chai sold on every street of the mohalla, hundreds of streets in a row. People came all day. Some asked, "How many cups in streets 120 to 480?" Others said, "Oops, street 300 is actually 5 more."

Adding 360 numbers per question was slow. Keeping a total for every possible range was impossible. And a fancy tree felt like too much for a chai stall.

Mira had the simple middle path. "Divide the streets into shelves of equal size. On each shelf, stick a note with that shelf's total." To answer a question, add the single numbers at the ragged ends, and for all the full shelves in between just read the notes.

When a street changes, fix the number and re-write only that one shelf's note. Not too many notes, and not too many numbers per shelf. Choosing shelf size about the square root of the street count balances both. This idea is square-root decomposition.

How to spot this problem, and where you need it

You need quick answers about ranges of a list while the list is also being updated, and rescanning the range every time is slow, but a more complex structure feels like overkill.

Signs you need it

  • You have both "change one value" and "answer for a range from L to R" operations, mixed together.
  • A plain loop over the range is too slow, but a full-sized prefix-sum rebuild after every update is also too slow.
  • The summary you need (sum, min, max, count) is easy to store per group.

Where to use it in a project

  • Dashboards with live edits and range totals shown to the user.
  • Counting flagged records in ranges while flags are toggled throughout the day.
  • Chunked storage or paged tables where each chunk keeps a small summary in its header.

The solution

Choose a block size near the square root of the list length (for 10,000 items, blocks of 100). Store a summary for each block. To update an item, change it and recompute only its block summary. To answer a range, add up the summaries of whole blocks inside it and check item by item only the partial blocks at both ends.

Payoff: Before: up to 10,000 items checked per question. After: a few hundred steps, easily fast enough for live screens.

Explain it like I am 8

A big library has 1,000 books in 30 shelves. To count sad-looking books between two spots, you do not count every book: you read the sign on each full shelf and count the loose books at the two ends yourself.

How it works, step by step

  1. Choose a block size near the square root of n (9 items: blocks of 3).
  2. Pre-compute a summary (here a sum) for every block.
  3. Query [l, r]: add single items at the left edge and the right edge, then add the summary of each block fully inside.
  4. Update one item: change it and fix the summary of its block (add the difference).
  5. Each operation touches at most about two partial blocks plus all full blocks: roughly √n pieces of work.

The code in four languages

PHP

<?php
// Range sum with point updates using blocks of about sqrt(n) items.
class SqrtSum {
    private array $a;
    private array $blocks = [];
    private int $size;

    function __construct(array $a) {
        $this->a = $a;
        $this->size = max(1, (int) sqrt(count($a)));          // block size
        foreach ($a as $i => $v) {
            $b = intdiv($i, $this->size);
            $this->blocks[$b] = ($this->blocks[$b] ?? 0) + $v; // sticky note per block
        }
    }

    function update(int $i, int $value): void {
        $this->blocks[intdiv($i, $this->size)] += $value - $this->a[$i];   // fix one note
        $this->a[$i] = $value;
    }

    function query(int $l, int $r): int {                      // inclusive
        $sum = 0;
        $i = $l;
        while ($i <= $r) {
            if ($i % $this->size === 0 && $i + $this->size - 1 <= $r) {
                $sum += $this->blocks[intdiv($i, $this->size)];   // whole block: read the note
                $i += $this->size;
            } else {
                $sum += $this->a[$i];                             // stray item: add it
                $i++;
            }
        }
        return $sum;
    }
}

$s = new SqrtSum([5, 2, 7, 1, 4, 3, 6, 8, 2]);
echo $s->query(1, 7), "\n";    // 31
$s->update(4, 10);
echo $s->query(1, 7), "\n";    // 37

JavaScript

// Range sum with point updates using blocks of about sqrt(n) items.
class SqrtSum {
  constructor(a) {
    this.a = a.slice();
    this.size = Math.max(1, Math.floor(Math.sqrt(a.length)));   // block size
    this.blocks = [];
    a.forEach((v, i) => {
      const b = Math.floor(i / this.size);
      this.blocks[b] = (this.blocks[b] || 0) + v;                // sticky note per block
    });
  }

  update(i, value) {
    this.blocks[Math.floor(i / this.size)] += value - this.a[i]; // fix one note
    this.a[i] = value;
  }

  query(l, r) {                                                  // inclusive
    let sum = 0, i = l;
    while (i <= r) {
      if (i % this.size === 0 && i + this.size - 1 <= r) {
        sum += this.blocks[i / this.size];                       // whole block: read the note
        i += this.size;
      } else {
        sum += this.a[i];                                        // stray item: add it
        i++;
      }
    }
    return sum;
  }
}

const s = new SqrtSum([5, 2, 7, 1, 4, 3, 6, 8, 2]);
console.log(s.query(1, 7));   // 31
s.update(4, 10);
console.log(s.query(1, 7));   // 37

Java

public class Main {
    // Range sum with point updates using blocks of about sqrt(n) items.
    static class SqrtSum {
        private final int[] a;
        private final int[] blocks;
        private final int size;

        SqrtSum(int[] input) {
            a = input.clone();
            size = Math.max(1, (int) Math.sqrt(a.length));          // block size
            blocks = new int[(a.length + size - 1) / size];
            for (int i = 0; i < a.length; i++) {
                blocks[i / size] += a[i];                            // sticky note per block
            }
        }

        void update(int i, int value) {
            blocks[i / size] += value - a[i];                        // fix one note
            a[i] = value;
        }

        int query(int l, int r) {                                    // inclusive
            int sum = 0;
            int i = l;
            while (i <= r) {
                if (i % size == 0 && i + size - 1 <= r) {
                    sum += blocks[i / size];                         // whole block: read the note
                    i += size;
                } else {
                    sum += a[i];                                     // stray item: add it
                    i++;
                }
            }
            return sum;
        }
    }

    public static void main(String[] args) {
        SqrtSum s = new SqrtSum(new int[]{5, 2, 7, 1, 4, 3, 6, 8, 2});
        System.out.println(s.query(1, 7));    // 31
        s.update(4, 10);
        System.out.println(s.query(1, 7));    // 37
    }
}

Go

package main

import (
	"fmt"
	"math"
)

// SqrtSum answers range sums with point updates using blocks of about sqrt(n) items.
type SqrtSum struct {
	a      []int
	blocks []int
	size   int
}

func NewSqrtSum(input []int) *SqrtSum {
	a := append([]int(nil), input...)
	size := max(1, int(math.Sqrt(float64(len(a))))) // block size
	blocks := make([]int, (len(a)+size-1)/size)
	for i, v := range a {
		blocks[i/size] += v // sticky note per block
	}
	return &SqrtSum{a, blocks, size}
}

func (s *SqrtSum) Update(i, value int) {
	s.blocks[i/s.size] += value - s.a[i] // fix one note
	s.a[i] = value
}

// Query returns the sum of a[l..r], inclusive.
func (s *SqrtSum) Query(l, r int) int {
	sum := 0
	i := l
	for i <= r {
		if i%s.size == 0 && i+s.size-1 <= r {
			sum += s.blocks[i/s.size] // whole block: read the note
			i += s.size
		} else {
			sum += s.a[i] // stray item: add it
			i++
		}
	}
	return sum
}

func main() {
	s := NewSqrtSum([]int{5, 2, 7, 1, 4, 3, 6, 8, 2})
	fmt.Println(s.Query(1, 7)) // 31
	s.Update(4, 10)
	fmt.Println(s.Query(1, 7)) // 37
}

Time: O(√n) per query and per update · Extra space: O(n). Slower than a segment tree (log n), but far simpler, and works for odd summaries.

Watch out for

  • Forgetting to fix the block summary when an item changes, so notes drift out of date.
  • Wrong block boundaries: the last block may be shorter than the others when n is not a perfect multiple.
  • Block size 1 (a note per item) or block size n (one note only) loses all benefit. Aim near √n.

Quick check

  1. Why choose block size near √n?
    • It balances single items against number of blocks
    • It makes the array sorted
    • It is the only size that works
  2. One item changes. How much do we recompute?
    • All blocks
    • Only the item's own block summary
    • Nothing
  3. Which part of a query is read from sticky notes?
    • The two ragged ends
    • The very first item
    • Blocks fully inside the range