Skip to content

Array Scan

Traverse an array sequentially to compute an aggregate or apply a function.

Array scan processes elements sequentially from left to right (or right to left). It forms the basis of many algorithms, including aggregation, filtering, searching, and transformations.

You use it when every element must be inspected at least once.

Problem

Given an array AA of length nn, compute an aggregate value such as:

i=0n1A[i] \sum_{i=0}^{n-1} A[i]

or apply a function to each element.

Algorithm

Sequential scan:

scan(A, f, init):
    result = init

    for i from 0 to length(A) - 1:
        result = f(result, A[i])

    return result

Example

Let

A=[8,3,5,1,9] A = [8, 3, 5, 1, 9]

Compute the sum:

stepelementresult
188
2311
3516
4117
5926

Return:

26 26

Correctness

The scan maintains an invariant: after processing index ii, the variable result contains the aggregate of elements from index 00 through ii.

Each iteration updates the result by combining the current value with the next element. After the final iteration, all elements have been processed exactly once, so the result contains the aggregate over the entire array.

Complexity

operationtime
scanO(n)O(n)

Space usage:

O(1) O(1)

for simple aggregates.

When to Use

Array scan is appropriate when:

  • every element must be examined
  • computing sums, counts, or reductions
  • building prefix or cumulative results
  • applying transformations in sequence

It is less suitable when:

  • only a small subset of elements is needed
  • random access queries dominate

Implementation

def scan(a, f, init):
    result = init
    for x in a:
        result = f(result, x)
    return result
func Scan[T any, R any](a []T, init R, f func(R, T) R) R {
    result := init
    for _, x := range a {
        result = f(result, x)
    }
    return result
}