Search⌘ K
AI Features

Algorithm Patterns That Show Up in the Screen

Apply essential algorithm patterns to solve sum and range problems efficiently. Use dictionaries to track counts, two pointers for sorted inputs, sliding windows for contiguous ranges, prefix sums to count exact sums with negative values, heaps to maintain top-k values, and breadth-first search (BFS) to explore graphs and grids. Identify each pattern's underlying invariants and discard rules, and adapt your approach to different problem constraints while optimizing performance.

Find a pair of values that sums to a target in a sorted list. Count the contiguous ranges that sum to a target in a list with negative numbers. Both prompts are about sums, but they need different algorithms.

What decides the choice is why each algorithm can safely ignore some candidates. If you understand that, you can adapt when a screen question looks like a familiar template but breaks one of its assumptions.

How to choose a pattern

Before coding, answer four questions:

  1. What object is requested? A pair, a contiguous range, a group, a top-k ranking or a path.

  2. Which constraints change correctness? Sorted input, negative values, duplicates, endpoint rules, edge weights.

  3. What state will you keep, and what does it mean? That meaning is your invariant.

  4. Why is it safe to discard what you discard?

A pattern is justified by its invariant and its discard argument, not by a familiar word in the prompt. Public preparation guides mention these patterns in screens, but they are reported possibilities, not an official list.

Pattern 1: Dictionary for counts and groups

Lesson 4 used a dictionary for keyed totals. The same tool covers counts and groups, as long as the key and value match the contract:

  • For [4, 4, 1], counts are {4: 2, 1: 1}. A set would lose the repeat.

  • When identity is account plus symbol, both belong in the key.

  • 'east' in totals asks whether a key exists. totals['east'] == 0 asks about its value. They are different questions.

Dictionary lookups take constant time on average, so one pass over n items is O(n).

Pattern 2: Two pointers on sorted input

Take ascending values [1, 2, 4, 7, 11] and target 10. Start at both ends:

  1. 1 + 11 = 12, too large: move the right pointer in.

  2. 1 + 7 = 8, too small: move the left pointer in.

  3. 2 + 7 = 9 ...