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.
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 problem | Pattern |
|---|---|
| Sorted array; find a pair/triplet with a target sum | Two pointers, opposite ends |
| Remove duplicates / move zeros in place | Two pointers, same direction (read/write) |
| Palindrome, reverse | Two pointers, opposite ends |
| Longest/shortest contiguous subarray or substring with a condition | Variable sliding window |
| Something about every window of size k | Fixed sliding window |
| Count subarrays with exactly k of something | atMost(k) − atMost(k−1) |
| Subarray sum with negative numbers | Not 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) == 9Template 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") == 3Minimum 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) == 7Know 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.
Bugs that cost the round
- Off-by-one in window length: it's
right - left + 1. - Shrinking with
ifinstead ofwhile: 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
- "Brute force checks every subarray: O(n²)."
- "The condition is monotonic: growing the window only makes it more invalid, so I can shrink from the left instead of restarting."
- "Each pointer moves forward at most n times, so it's O(n) time and O(k) space for the counts."
Practice list
| Problem | Template |
|---|---|
| Two Sum II, 3Sum, Container With Most Water | Opposite ends |
| Remove Duplicates, Move Zeroes | Read/write |
| Maximum Average Subarray I | Fixed window |
| Longest Substring Without Repeating Characters | Variable window |
| Longest Repeating Character Replacement | Variable window |
| Minimum Window Substring | Variable window (shrink to minimise) |
| Subarrays with K Different Integers | Exactly-k trick |
Related
- Binary search interview patterns
- Graph interview patterns
- Dynamic programming patterns
- How to crack a DSA coding round
Frequently asked questions
Was this article useful?
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.
More from the blog
The Coding Interview Guide for Software Engineers in India (2026)
Everything a software engineer in India needs for coding rounds: how online assessments, DSA rounds, machine coding and CS fundamentals differ by company type, a 10-week preparation plan, and how to perform in the room.
Dynamic Programming Interview Patterns: A Practical Guide
Dynamic programming becomes manageable when you learn the handful of patterns behind it. A step-by-step method, the main DP families with templates and classic problems, and how to move from recursion to tabulation.
Python vs Java vs C++ for Coding Interviews: Which Should You Use?
Which language to pick for DSA interviews: speed of writing, standard library strength, performance limits, and what interviewers care about. Practical guidance for Indian placements and product-company loops.
Discussion
No comments yet. Been through an interview like this? Your experience could help the next candidate.