Skip to main content
DSA & CodingInterview Prep

Sliding Window and Two Pointers: Coding Interview Patterns with Templates

How to recognise sliding window and two-pointer problems, the four templates that cover most of them, worked Python solutions to classic interview questions, and the bugs that cost people the round.

InterviewPilot TeamNovember 25, 20266 min read

Sliding window and two pointers show up in a large share of online assessments and first-round DSA interviews, because they test whether you can turn an obvious O(n²) loop into O(n). This guide is part of our coding interview guide for India; the full pattern list is in 15 DSA patterns.

How to recognise them

Clue in the problemPattern
Sorted array; find a pair/triplet with a target sumTwo pointers, opposite ends
Remove duplicates / move zeros in placeTwo pointers, same direction (read/write)
Palindrome, reverseTwo pointers, opposite ends
Longest/shortest contiguous subarray or substring with a conditionVariable sliding window
Something about every window of size kFixed sliding window
Count subarrays with exactly k of somethingatMost(k) − atMost(k−1)
Subarray sum with negative numbersNot a window: prefix sum + hash map

Template 1: two pointers from both ends

Two Sum II (sorted input): move the left pointer right if the sum is too small, the right pointer left if it's too big.

def two_sum_sorted(nums: list[int], target: int) -> tuple[int, int] | None:
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        s = nums[lo] + nums[hi]
        if s == target:
            return lo, hi
        if s < target:
            lo += 1
        else:
            hi -= 1
    return None
 
assert two_sum_sorted([1, 3, 4, 6, 9], 10) == (0, 4)

Why it works: if nums[lo] + nums[hi] is too small, no pair using nums[lo] with anything left of hi can reach the target, so lo is safe to discard.

3Sum is this template inside a loop: sort, fix i, then two-pointer the rest, skipping duplicates.

def three_sum(nums: list[int]) -> list[list[int]]:
    nums.sort()
    out = []
    for i in range(len(nums) - 2):
        if i and nums[i] == nums[i - 1]:
            continue
        lo, hi = i + 1, len(nums) - 1
        while lo < hi:
            s = nums[i] + nums[lo] + nums[hi]
            if s < 0:
                lo += 1
            elif s > 0:
                hi -= 1
            else:
                out.append([nums[i], nums[lo], nums[hi]])
                lo += 1
                while lo < hi and nums[lo] == nums[lo - 1]:
                    lo += 1
                hi -= 1
    return out
 
assert three_sum([-1, 0, 1, 2, -1, -4]) == [[-1, -1, 2], [-1, 0, 1]]

Template 2: read/write pointers (in place)

Remove duplicates from a sorted array: write marks where the next unique value goes.

def dedupe_sorted(nums: list[int]) -> int:
    write = 0
    for read in range(len(nums)):
        if read == 0 or nums[read] != nums[read - 1]:
            nums[write] = nums[read]
            write += 1
    return write
 
arr = [1, 1, 2, 3, 3, 3, 4]
assert dedupe_sorted(arr) == 4 and arr[:4] == [1, 2, 3, 4]

Template 3: fixed-size window

Maximum sum of any k consecutive elements: add the new element, subtract the one that left.

def max_sum_k(nums: list[int], k: int) -> int:
    window = sum(nums[:k])
    best = window
    for i in range(k, len(nums)):
        window += nums[i] - nums[i - k]
        best = max(best, window)
    return best
 
assert max_sum_k([2, 1, 5, 1, 3, 2], 3) == 9

Template 4: variable-size window

The general shape: expand right every step; shrink left while the window is invalid; record the answer.

Longest substring without repeating characters:

def longest_unique(s: str) -> int:
    last_seen: dict[str, int] = {}
    left = best = 0
    for right, ch in enumerate(s):
        if ch in last_seen and last_seen[ch] >= left:
            left = last_seen[ch] + 1          # jump past the duplicate
        last_seen[ch] = right
        best = max(best, right - left + 1)
    return best
 
assert longest_unique("abcabcbb") == 3
assert longest_unique("pwwkew") == 3

Minimum window substring (the hard one): grow until the window contains every needed character, then shrink as far as possible while it still does.

from collections import Counter
 
def min_window(s: str, t: str) -> str:
    need = Counter(t)
    missing = len(t)
    left = 0
    best = (float("inf"), 0, 0)
    for right, ch in enumerate(s):
        if need[ch] > 0:
            missing -= 1
        need[ch] -= 1
        while missing == 0:                     # window is valid: try to shrink
            if right - left + 1 < best[0]:
                best = (right - left + 1, left, right + 1)
            need[s[left]] += 1
            if need[s[left]] > 0:
                missing += 1
            left += 1
    return s[best[1]:best[2]] if best[0] != float("inf") else ""
 
assert min_window("ADOBECODEBANC", "ABC") == "BANC"

The "exactly k" trick

Counting subarrays with exactly k distinct values is awkward directly, but at most k is a clean window. So: exactly(k) = at_most(k) − at_most(k − 1).

from collections import defaultdict
 
def at_most_k_distinct(nums: list[int], k: int) -> int:
    count = defaultdict(int)
    left = total = 0
    for right, x in enumerate(nums):
        count[x] += 1
        while len(count) > k:
            count[nums[left]] -= 1
            if count[nums[left]] == 0:
                del count[nums[left]]
            left += 1
        total += right - left + 1          # subarrays ending at `right`
    return total
 
def exactly_k_distinct(nums: list[int], k: int) -> int:
    return at_most_k_distinct(nums, k) - at_most_k_distinct(nums, k - 1)
 
assert exactly_k_distinct([1, 2, 1, 2, 3], 2) == 7

Know the pattern but blank on the template mid-round?

InterviewPilot reads the problem off your screen and streams an approach, code and complexity analysis to an overlay that Zoom, Meet and Teams screen shares don't capture.

Try it freeHow the AI interview assistant works3 free sessions a day · Windows 10/11 · no card required

Bugs that cost the round

  • Off-by-one in window length: it's right - left + 1.
  • Shrinking with if instead of while: the window may need to shrink by more than one.
  • Using a window on sums with negatives: shrinking no longer moves the sum in one direction.
  • Forgetting to skip duplicates in 3Sum, which produces repeated triplets.
  • Stale hash-map entries: in the unique-substring problem, check last_seen[ch] >= left.

How to explain it in the interview

  1. "Brute force checks every subarray: O(n²)."
  2. "The condition is monotonic: growing the window only makes it more invalid, so I can shrink from the left instead of restarting."
  3. "Each pointer moves forward at most n times, so it's O(n) time and O(k) space for the counts."

Practice list

ProblemTemplate
Two Sum II, 3Sum, Container With Most WaterOpposite ends
Remove Duplicates, Move ZeroesRead/write
Maximum Average Subarray IFixed window
Longest Substring Without Repeating CharactersVariable window
Longest Repeating Character ReplacementVariable window
Minimum Window SubstringVariable window (shrink to minimise)
Subarrays with K Different IntegersExactly-k trick

Frequently asked questions

A sliding window is a special case of two pointers where both move in the same direction and the elements between them form the current answer candidate. Classic two pointers often move towards each other from opposite ends.

The left pointer only moves forward and can move at most n times in total across the whole run, so total work is O(n).

Not for sum conditions. Shrinking only works when adding elements moves the condition in one direction. With negatives, use prefix sums with a hash map instead.

Two Sum II, 3Sum, Container With Most Water, Longest Substring Without Repeating Characters, Minimum Window Substring, Longest Repeating Character Replacement and Subarrays with K Different Integers.

Was this article useful?

Discussion

No comments yet. Been through an interview like this? Your experience could help the next candidate.

You’re posting anonymously — it appears after a quick review. Sign in to post under your name instantly.
0/2000

Bring backup into your next round.

Install InterviewPilot, upload your resume, and walk in with structured answers a keystroke away — visible to you and nobody else.