Knowing What to Track

Pick the few numbers that let you answer the question at each step, and update them in O(1) as you scan: letter counts, a matched counter, a balance, an XOR.

Overview

Many array and string problems have a slow solution that looks at every window or every pair, and a fast one that scans the input once. The difference between them is almost always the same: the fast solution carries a small amount of state and updates it in O(1) at each step, instead of recomputing something from scratch.

Knowing what to track is the habit of asking, before you code: what do I need to know at this position to answer the question, and can I keep that up to date as I move? The state is usually one of a handful of things, and each section of this chapter takes one of them.

  • How often each value appears: track a count per value, in a hash map or an array of 26 for lowercase letters. First unique character and Valid Sudoku work this way.
  • Whether two collections have the same counts: track the counts of a moving window, plus a matched counter, as in Find All Anagrams and Permutation in String.
  • Whether a window covers a required set: track the counts, plus how many required values are satisfied, as in Minimum Window Substring.
  • Opens and closes staying in step: track one balance counter, as in Valid parentheses and the minimum adds to make a string valid.
  • Values that come in pairs: track a running XOR, as in Single Number.
  • Which items are 'the same' under rearranging: track a signature and use it as a hash key, as in Group Anagrams.

Counting

A frequency map turns 'is this value repeated?' from a comparison of pairs into a lookup. For first unique character, one pass counts the letters and a second pass returns the first letter whose count is 1.

Try it on the word 'stress', where the first pass counts s three times and t, r and e once each. Scanning the word again, 's' has count 3, so it is skipped, and 't' is the first letter with count 1. Two passes over n letters is O(n) time. The map has at most 26 keys for lowercase English letters, so the space is O(1) for that alphabet, or O(k) for an alphabet of size k.

In Python, collections.Counter is the usual tool: reading a missing key returns 0 instead of raising, so you never test for membership before you count. When the problem promises lowercase English letters, a list of 26 integers indexed by ord(ch) - ord('a') does the same job with no hashing.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio