awelgorithms

The array state pattern: how to spot it

Updated

Many array problems are solved in one pass by carrying a little state forward instead of looking back: the best value so far, a running minimum, a write index, or prefix and suffix products. The skill is choosing what to remember.

When to reach for it

The usual shape

best = worst_possible
state = initial               # running min, write index, prefix product…
for x in items:
    best = better(best, combine(state, x))
    state = update(state, x)
return best

5 LeetCode arrays problems, easiest first

  1. Best Time to Buy and Sell Stock easy

    Track the cheapest buy behind you. Profit is price minus that min.

  2. Merge Sorted Array easy

    Write from the end so you do not clobber unread values in nums1.

  3. Move Zeroes easy

    Write pointer keeps the next non-zero. Zeros fill the tail.

  4. Rotate Array medium

    k wraps with modulo. Reverse-three-times or extra buffer both count.

  5. Product of Array Except Self medium

    Left products times right products. No division; zeros make division illegal.

check which skills you have 10 minutes, free, no account.

Other patterns