Learn how frequency counters, two pointers, and sliding windows guide efficient solutions to common coding problems.
An algorithm pattern is a way of organizing work that applies to more than one problem. To choose a pattern, ask what information lets you safely skip work on the next step.
Start with one string, "ABBA". Counting letters gives the same answer even if the letters are rearranged. Checking for a palindrome requires comparing mirrored positions. Looking for adjacent repeats requires keeping a contiguous pair as it moves through AB, BB, and BA.
Now apply those choices to other inputs:
| Problem | What to keep | Why the next step is safe |
|---|---|---|
| Do two words contain the same letters in the same quantities? | A count for each character | Consuming one count per letter accounts for every occurrence. |
| Which two values in a sorted array sum to a target? | The two ends of the remaining range | Ordering lets one comparison eliminate an entire endpoint. |
| Which consecutive four values have the largest sum? | A running sum and window bounds | Neighboring windows share three values, so only two edge values affect the update. |
Some problems combine patterns. For example, a sliding window can use a map to track the character counts within its current bounds.
Start with frequency counters, then move through two pointers and sliding windows: