Two pointers uses two indexes that move through an array, often from both ends or at different speeds, to replace a nested loop with one pass. Sliding window keeps a contiguous range that grows and shrinks while you update a running total or count. Both usually turn O(n squared) brute force into O(n).
On this page
Two pointers vs sliding window: the differenceTwo pointers: five problemsSliding window: five problemsComplexity summary and how to recognise each patternFrequently asked questionsThese two patterns cover a large share of array and string questions in coding rounds. The page gives five problems for each, with the brute-force version beside the optimised one, so you can see exactly which line of work disappears.
Every block was run with Python 3 on 1 December 2026. Each one prints the brute-force answer and the optimised answer side by side, and they agree. Problem numbers are LeetCode's, confirmed through LeetCode's own site on that date.
- 1Read the inputArray or string, contiguous?
- 2Sorted or paired?Try two pointers
- 3Contiguous range?Try a window
- 4Write the invariantWhat stays true as you move
- 5Check the costEach index moves once
Two pointers vs sliding window: the difference
In two pointers, the two indexes are related by a rule, such as one at each end moving inward, or one slow and one fast. You decide which pointer to move by comparing the values they point at. In a sliding window, the two indexes (left and right) mark the edges of a contiguous range, and the question is about that range: its sum, its distinct characters, its length.
| Two pointers | Sliding window | |
|---|---|---|
| Typical input | Sorted array, or a string to check from both ends | Array or string where the answer is a contiguous subarray or substring |
| Signal words | sorted, pair, triplet, palindrome, in place, remove duplicates | longest, shortest, subarray, substring, at most k, contiguous, window of size k |
| Pointer movement | Opposite ends inward, or slow and fast same direction | Right edge grows every step, left edge shrinks only when the window is invalid |
| Why it is fast | Each pointer moves at most n steps, total O(n) | Each element enters and leaves the window once, total O(n) |
| Extra memory | O(1) usually | O(1) for sums, O(k) for counts of distinct items |
Sliding window is a special case of two pointers where both pointers move the same way. The distinction matters because it tells you what to track. For the sorted-array problems you track nothing but the two values. For windows you track a running sum or a dictionary of counts.
Both patterns depend on time complexity reasoning, so skim that page first if O(n) versus O(n squared) is still fuzzy.
Two pointers: five problems
1. Two Sum in a sorted array (LeetCode 167)
Find two numbers that add to a target. Brute force tries every pair: O(n squared). Because the array is sorted, put one pointer at each end. If the sum is too small, move the left pointer right to get a bigger number; if too big, move the right pointer left. That is O(n) time and O(1) space.
def two_sum_brute(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return []
def two_sum_pointers(nums, target):
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 []
nums = [2, 7, 11, 15, 19, 24]
print(two_sum_brute(nums, 26), two_sum_pointers(nums, 26))
print(two_sum_brute(nums, 100), two_sum_pointers(nums, 100))Output: [0, 5] [0, 5] (2 + 24 = 26), then [] [] when no pair makes 100.
2. Valid Palindrome (LeetCode 125)
Ignore case and non-alphanumeric characters, then check if the text reads the same both ways. The brute-force approach builds a cleaned, reversed copy: O(n) time, O(n) space. Two pointers walk inward, skipping junk characters, and compare in place: O(n) time, O(1) space. Here the win is memory, not time.
def is_palindrome_brute(s):
cleaned = "".join(ch.lower() for ch in s if ch.isalnum())
return cleaned == cleaned[::-1] # O(n) extra space
def is_palindrome_pointers(s):
lo, hi = 0, len(s) - 1
while lo < hi:
while lo < hi and not s[lo].isalnum():
lo += 1
while lo < hi and not s[hi].isalnum():
hi -= 1
if s[lo].lower() != s[hi].lower():
return False
lo += 1
hi -= 1
return True # O(1) extra space
for text in ["A man, a plan, a canal: Panama", "race a car"]:
print(is_palindrome_brute(text), is_palindrome_pointers(text))Output: True True for the Panama sentence and False False for race a car.
3. Container With Most Water (LeetCode 11)
Given wall heights, pick two walls that hold the most water: area is the shorter height times the gap. Brute force checks all pairs, O(n squared). Start with the widest pair and move the pointer at the shorter wall inward. Moving the taller one can never help, because the shorter wall still limits the height while the gap shrinks.
def max_area_brute(h):
best = 0
for i in range(len(h)):
for j in range(i + 1, len(h)):
best = max(best, min(h[i], h[j]) * (j - i))
return best
def max_area_pointers(h):
lo, hi, best = 0, len(h) - 1, 0
while lo < hi:
best = max(best, min(h[lo], h[hi]) * (hi - lo))
if h[lo] < h[hi]: # the shorter wall cannot do better with a narrower gap
lo += 1
else:
hi -= 1
return best
h = [1, 8, 6, 2, 5, 4, 8, 3, 7]
print(max_area_brute(h), max_area_pointers(h))Output: 49 49. The best pair is the walls of height 8 and 7, seven positions apart.
4. Remove Duplicates from Sorted Array (LeetCode 26)
Modify the array in place so each value appears once, and return the new length. A slow pointer marks the end of the unique prefix; a fast pointer scans ahead. Copying through sorted(set(...)) works but needs O(n) extra memory and ignores the in-place requirement.
def remove_duplicates_brute(nums):
unique = sorted(set(nums)) # O(n) extra space
nums[:len(unique)] = unique
return len(unique)
def remove_duplicates_pointers(nums):
if not nums:
return 0
slow = 0
for fast in range(1, len(nums)):
if nums[fast] != nums[slow]:
slow += 1
nums[slow] = nums[fast]
return slow + 1 # O(1) extra space
a = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
b = a[:]
k1, k2 = remove_duplicates_brute(a), remove_duplicates_pointers(b)
print(k1, a[:k1])
print(k2, b[:k2])Output: 5 [0, 1, 2, 3, 4] twice.
5. 3Sum (LeetCode 15)
Find all unique triplets that sum to zero. Brute force tries every triple: O(n cubed). Sort the array, fix one number, and run the two-pointer pair search on the rest: O(n squared) overall, since the sort costs only O(n log n). Skipping repeated anchor values keeps the results unique.
def three_sum_brute(nums):
n, found = len(nums), set()
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if nums[i] + nums[j] + nums[k] == 0:
found.add(tuple(sorted((nums[i], nums[j], nums[k]))))
return sorted(found)
def three_sum_pointers(nums):
nums, out = sorted(nums), []
for i in range(len(nums) - 2):
if i and nums[i] == nums[i - 1]:
continue # skip duplicate anchors
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
hi -= 1
while lo < hi and nums[lo] == nums[lo - 1]:
lo += 1
return out
nums = [-1, 0, 1, 2, -1, -4]
print(three_sum_brute(nums))
print(three_sum_pointers(nums))Output: [(-1, -1, 2), (-1, 0, 1)] from both versions. This problem shows the pattern as a building block: a harder question reduced to the easy one inside a loop.
Sliding window: five problems
1. Maximum sum of a subarray of size k (LeetCode 643 is the average version)
The window size is fixed. Brute force re-sums k numbers for every start: O(n times k). The window instead adds the entering element and subtracts the leaving one: O(n).
def max_sum_brute(a, k):
return max(sum(a[i:i + k]) for i in range(len(a) - k + 1))
def max_sum_window(a, k):
window = sum(a[:k])
best = window
for i in range(k, len(a)):
window += a[i] - a[i - k] # add the new element, drop the old one
best = max(best, window)
return best
a = [2, 1, 5, 1, 3, 2]
print(max_sum_brute(a, 3), max_sum_window(a, 3))Output: 9 9 (the window 5, 1, 3).
2. Longest Substring Without Repeating Characters (LeetCode 3)
The size is variable. Brute force restarts from every index and extends until a repeat: O(n squared). The window keeps the last index of each character; when the right character already sits inside the window, the left edge jumps just past it.
def longest_unique_brute(s):
best = 0
for i in range(len(s)):
seen = set()
for j in range(i, len(s)):
if s[j] in seen:
break
seen.add(s[j])
best = max(best, j - i + 1)
return best
def longest_unique_window(s):
last, left, best = {}, 0, 0
for right, ch in enumerate(s):
if ch in last and last[ch] >= left:
left = last[ch] + 1 # jump past the earlier copy
last[ch] = right
best = max(best, right - left + 1)
return best
for s in ["abcabcbb", "bbbbb", "pwwkew"]:
print(s, longest_unique_brute(s), longest_unique_window(s))Output: abcabcbb 3 3, bbbbb 1 1, pwwkew 3 3.
3. Minimum Size Subarray Sum (LeetCode 209)
Find the shortest subarray with sum at least the target, in an array of positive numbers. Extend the right edge until the sum is large enough, then shrink from the left while it stays large enough, recording the length each time. Positivity is what makes shrinking safe: removing an element can only lower the sum.
def min_len_brute(target, nums):
best = float("inf")
for i in range(len(nums)):
total = 0
for j in range(i, len(nums)):
total += nums[j]
if total >= target:
best = min(best, j - i + 1)
break
return 0 if best == float("inf") else best
def min_len_window(target, nums):
left = total = 0
best = float("inf")
for right, x in enumerate(nums):
total += x
while total >= target: # shrink while still valid
best = min(best, right - left + 1)
total -= nums[left]
left += 1
return 0 if best == float("inf") else best
nums = [2, 3, 1, 2, 4, 3]
print(min_len_brute(7, nums), min_len_window(7, nums))
print(min_len_brute(100, nums), min_len_window(100, nums))Output: 2 2 (the pair 4, 3 sums to 7) and 0 0 when no subarray reaches 100.
4. Max Consecutive Ones III (LeetCode 1004)
Longest run of ones if you may flip at most k zeros. The window is valid while it contains at most k zeros; when a new zero breaks that, shrink from the left until it is valid again. This is the template for every "at most k" window question.
def longest_ones_brute(nums, k):
best = 0
for i in range(len(nums)):
zeros = 0
for j in range(i, len(nums)):
zeros += nums[j] == 0
if zeros > k:
break
best = max(best, j - i + 1)
return best
def longest_ones_window(nums, k):
left = zeros = best = 0
for right, x in enumerate(nums):
zeros += x == 0
while zeros > k: # too many zeros: shrink from the left
zeros -= nums[left] == 0
left += 1
best = max(best, right - left + 1)
return best
nums = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0]
print(longest_ones_brute(nums, 2), longest_ones_window(nums, 2))Output: 6 6.
5. Find All Anagrams in a String (LeetCode 438)
Return every start index where a window of length len(p) is a rearrangement of p. Sorting each window costs O(n times k log k). A character-count window updates one count in and one count out per step.
from collections import Counter
def find_anagrams_brute(s, p):
need = sorted(p)
return [i for i in range(len(s) - len(p) + 1) if sorted(s[i:i + len(p)]) == need]
def find_anagrams_window(s, p):
need, window, out = Counter(p), Counter(), []
for i, ch in enumerate(s):
window[ch] += 1
if i >= len(p):
old = s[i - len(p)]
window[old] -= 1
if window[old] == 0:
del window[old] # keep the Counters comparable
if window == need:
out.append(i - len(p) + 1)
return out
print(find_anagrams_brute("cbaebabacd", "abc"), find_anagrams_window("cbaebabacd", "abc"))Output: [0, 6] [0, 6], the windows cba and bac.
Complexity summary and how to recognise each pattern
| Problem | Pattern | Brute force | Optimised | Extra space |
|---|---|---|---|---|
| Two Sum, sorted (167) | Two pointers, opposite ends | O(n squared) | O(n) | O(1) |
| Valid Palindrome (125) | Two pointers, opposite ends | O(n) | O(n) | O(n) down to O(1) |
| Container With Most Water (11) | Two pointers, opposite ends | O(n squared) | O(n) | O(1) |
| Remove Duplicates (26) | Two pointers, slow and fast | O(n log n) | O(n) | O(n) down to O(1) |
| 3Sum (15) | Sort plus two pointers | O(n cubed) | O(n squared) | O(1) besides output |
| Fixed-size window sum (643) | Fixed window | O(n times k) | O(n) | O(1) |
| Longest unique substring (3) | Variable window with map | O(n squared) | O(n) | O(min(n, alphabet)) |
| Minimum Size Subarray Sum (209) | Variable window, shrink while valid | O(n squared) | O(n) | O(1) |
| Max Consecutive Ones III (1004) | Variable window, at most k | O(n squared) | O(n) | O(1) |
| Find All Anagrams (438) | Fixed window with counts | O(n k log k) | O(n) | O(alphabet) |
Recognition checklist
- The input is sorted, or you may sort it, and you need a pair or triple with a property: two pointers.
- The problem says in place, or asks you to remove or partition without extra memory: slow and fast pointers.
- The answer is a contiguous subarray or substring, and the words longest, shortest or at most k appear: sliding window.
- A fixed length k is given: fixed window. No length given and you maximise or minimise it: variable window.
- Negative numbers appear in a sum-based window problem: the shrink step is no longer safe; try prefix sums with a hash map instead.
- Both pointers only ever move forward: that is what guarantees O(n). If one has to step back, rethink.
For the same ideas applied to sorted data, see binary search explained and sorting algorithms. To place these patterns in a longer study plan, use the LeetCode patterns roadmap.
Frequently asked questions
What is the two pointers technique?
It uses two indexes into an array or string, moved by a rule, to avoid a nested loop. Common forms are one pointer at each end moving inward on a sorted array, and a slow and a fast pointer moving the same way for in-place edits. Each pointer moves at most n steps, so the total is O(n).
What is the sliding window technique?
A window is a contiguous range of an array or string, marked by a left and a right index. You slide it by moving the right edge in, updating a running sum or count, and moving the left edge out when the window becomes invalid. Every element enters and leaves once, so the time is O(n).
What is the difference between two pointers and sliding window?
Sliding window is two pointers where both move the same direction and the question is about the range between them. Classic two pointers often starts from both ends of a sorted array and compares the two values. If the problem says longest or shortest subarray, think window; if it says pair in a sorted array, think two pointers.
How do I know when to use a sliding window?
Look for a contiguous subarray or substring, plus a goal such as longest, shortest, maximum sum, or at most k distinct or flipped items. If you can describe the answer as a range [left, right] that you extend and trim, a window fits. If the elements can be non-contiguous, it does not.
Why is sliding window O(n) when it has a loop inside a loop?
The inner while loop moves the left pointer, which never moves backwards and never passes the right pointer. Across the whole run, left advances at most n times and right at most n times. Total work is at most 2n steps, so it is O(n), not O(n squared).
Does sliding window work with negative numbers?
Not for sum-based questions that rely on shrinking. With positives, removing an element lowers the sum, so shrinking is safe. With negatives, that breaks, so use prefix sums with a hash map for problems like subarray sum equals k. Count-based windows, such as distinct characters, are not affected.
Learn this with mentors
Programmes for builders and engineers with admissions open: live classes, mentors and project work.


