692. Simulate a work-efficient parallel prefix sum
Why it matters Scans are the building block of GPU top-p sampling, radix sort and Mamba's parallel recurrence.
GPUs compute prefix sums with the Blelloch scan: an up-sweep that builds partial sums in a tree, then a down-sweep that distributes them.
Write blelloch_scan(x). len(x) is a power of 2. Up-sweep: for d = 1, 2, 4, ...: for i in range(2d - 1, n, 2d): a[i] += a[i - d]. Set a[n - 1] = 0. Down-sweep: for d = n/2, ..., 1: for i in range(2d - 1, n, 2d): t = a[i - d]; a[i - d] = a[i]; a[i] += t. Return (exclusive_scan, steps) where steps is the number of level loops executed (up plus down).
def blelloch_scan(x)Example 1
Input: blelloch_scan([3, 1, 7, 0])
Output: ([0, 3, 4, 11], 4)
Example 2
Input: x = [1, 2, 3, 4, 5, 6, 7, 8]
Output: ([0.0, 1.0, 3.0, 6.0, 10.0, 15.0, 21.0, 28.0], 6)
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Two loops over levels; each inner loop is what a GPU would run in parallel.
Hint 2
Up-sweep strides double.
Hint 3
Clear the last element.
Hint 4
Down-sweep: swap the left child with the parent, then add.
Common mistakes
- Assigning instead of adding in the down-sweep.
- Forgetting to clear the root.
Understand the idea
An exclusive prefix sum gives, at each position, the sum of everything before it. The Blelloch scan does it in two tree passes: an up-sweep builds partial sums so the last slot holds the total; then that slot is set to 0 and a down-sweep pushes sums back down, swapping and adding.
x = [2, 5, 1, 4]. Up-sweep d = 1: a[1] = 7, a[3] = 5, giving [2, 7, 1, 5]; d = 2: a[3] = 12, giving [2, 7, 1, 12]. Set a[3] = 0. Down-sweep d = 2: t = a[1] = 7, a[1] = 0, a[3] = 0 + 7 = 7, giving [2, 0, 1, 7]. d = 1: at i = 1, t = 2, a[0] = 0, a[1] = 2; at i = 3, t = 1, a[2] = 7, a[3] = 8. Result [0, 2, 7, 8], 4 level loops.
up-sweep for d = 1, 2, 4 while d < n, a[i] += a[i - d] at i = 2d - 1 stepping by 2d; zero a[n - 1]; down-sweep d from n/2 to 1
Each level loop is one step. Used in: stream compaction and radix sort.
Shapes and data flow
n = 8: up-sweep levels d = 1, 2, 4 (tree of partial sums) set root to 0 down-sweep d = 4, 2, 1 -> exclusive prefix sums
Topics
Companies1
- NVIDIA the topic appears in interview reports Nvidia Interview Guide 2026: GPU Architecture, CUDA Kernels, Distributed Training, and the AI Boom
From public interview reports and guides. Not affiliated with or endorsed by these companies.