Arrays and strings · Beginner

One pass with a running state

Carry a small summary of everything seen so far (a best, a count, a candidate) so each element is decided in O(1) and the whole scan is linear.

On this page
  1. The idea
  2. How to recognise it
  3. When not to use it
  4. Template
  5. Complexity
  6. Worked examples
  7. Pitfalls
  8. Practise it
  9. Learn the foundations
  10. References

The idea

Some problems look as if they need to compare every element with every earlier one, but only a tiny summary of the past matters: the best sum ending here, the cheapest price so far, a voting candidate and its margin. Keeping that summary up to date turns a quadratic scan into a linear one with O(1) memory.

The skill is choosing the summary and proving it is enough, usually with an invariant such as "best_ending_here is the largest sum of a subarray that ends at the current index".

How to recognise it

  • A single answer over a sequence (maximum, profit, majority, streak).
  • The decision for the current element depends only on an aggregate of earlier elements, not on which ones.
  • Required extra space is O(1).

When not to use it

  • The answer needs information about specific earlier elements (their positions, a lookup by value): use a hash map or a stack.
  • Queries ask about arbitrary ranges rather than prefixes: prefix sums or a tree.

Template

Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.

state = initial(a[0])
answer = value(state)
for x in a[1:]:
    state = step(state, x)           # O(1), uses only state and x
    answer = better(answer, value(state))
return answer

# Kadane: best subarray sum
best_here = best = a[0]
for x in a[1:]:
    best_here = max(x, best_here + x)  # extend the streak or restart at x
    best = max(best, best_here)
  • Initialise from the first element rather than 0 when all values could be negative.

Complexity

Time O(n), extra space O(1). One pass, constant work per element, a fixed number of variables.

Worked examples

Best streak in [2, −3, 4, −1, 2]

best_here: 2, then max(−3, −1) = −1, then max(4, 3) = 4, then 3, then 5. best tracks 2, 2, 4, 4, 5. The answer 5 is the subarray [4, −1, 2].

Pitfalls

  • Starting from 0 and returning 0 for an all-negative array.
  • Updating the answer before the state for the current element is computed.

Practise it

Solved problems with hints, a correctness argument and four tested implementations:

Learn the foundations

Related patterns

References

dsa.pattern.running-state · version 1