Sliding Window and Two Pointers in Coding Interviews

A surprising number of array and string questions in coding interviews collapse into one of two patterns: a sliding window or a pair of pointers. Recognising them early turns an O(n²) brute force into a clean O(n) answer, and interviewers notice when you name the pattern and explain why it fits.

When to reach for a sliding window

Look for phrases like "longest substring", "shortest subarray", "at most K distinct" or "sum at least target". The common thread is a contiguous range whose validity changes predictably as you grow or shrink it.

left = 0
for right in range(len(s)):
    add(s[right])
    while window_is_invalid():
        remove(s[left]); left += 1
    best = max(best, right - left + 1)

Say out loud what makes the window invalid and what you track (a counter, a running sum). That one sentence shows the interviewer you understand the invariant, not just the template.

When to use two pointers

Sorted arrays, pair sums, removing duplicates in place, and palindrome checks usually want two pointers moving toward each other or one fast and one slow. The key question: after comparing the two elements, can you safely discard one side? If yes, two pointers work.

Common mistakes

How to practise

Solve five problems of each pattern, then explain each solution aloud in under two minutes. Talking through the invariant is the part most candidates skip. If you want a second voice while you rehearse, AI coding interview assistant Linkjob AI can run mock coding rounds and give feedback on your explanation.

Disclosure: I'm part of the Linkjob AI team.