Skip to main content

Interview Patterns

Recognising the Pattern

Written by Updated

Interviewers do not have unlimited questions. Almost everything asked is a variation on a small set of patterns, and the wording gives away which one before you have written a line.

The signals

  • "contiguous", "substring", "subarray" with longest or shortest - sliding window.
  • "sorted" and "find a pair" - two pointers.
  • "has it appeared before", "count occurrences", "duplicate" - hash map or set.
  • "shortest path", "fewest steps", "nearest" in an unweighted graph - BFS.
  • "all paths", "is it connected", "detect a cycle" - DFS.
  • "how many ways", "maximum value", "minimum cost" with choices - dynamic programming.
  • "top k", "k largest", "k closest" - heap, or sort when k is close to n.
  • "matching brackets", "undo", "next greater" - stack.
  • "find in a sorted array", "minimum value that works" - binary search.
  • "generate all combinations or permutations" - backtracking.

Two questions that settle most cases

Is the input sorted, or would sorting help? If yes, two pointers and binary search are open to you.

Am I looking at a contiguous run, or any subset? Contiguous means sliding window. Any subset usually means DP or backtracking.

A worked example

"Given a string, find the length of the longest substring without repeating characters."

  1. "Substring" - contiguous. Not a subset problem.
  2. "Longest ... without" - a constraint that can break as the window grows.
  3. Contiguous plus a breakable constraint - sliding window.
  4. The constraint is about repeats, so the window needs a set or map.

The pattern, applied

javascript

function longestUnique(s) {
  const lastSeen = new Map()
  let start = 0
  let best = 0

  for (let end = 0; end < s.length; end++) {
    const ch = s[end]

    // Only jump forward — never move the window backwards.
    if (lastSeen.has(ch) && lastSeen.get(ch) >= start) {
      start = lastSeen.get(ch) + 1
    }

    lastSeen.set(ch, end)
    best = Math.max(best, end - start + 1)
  }

  return best
}

console.log(longestUnique("abcabcbb"))  // 3

The pattern was identified from four words in the question. That is the skill worth practising - not memorising solutions, but reading the statement.

When nothing matches

Write the brute force. It is always worth marks, it clarifies the problem, and the bottleneck it exposes usually points at the pattern you missed.