Two Pointers and Sliding Window Techniques

Introduction:
Many array and string problems have an obvious solution that checks every pair or every sub-array: two nested loops, O(n²) time. For 1,000 elements that is about a million steps, which is fine. For 1,000,000 elements it is a trillion, which is not.
Two pointers and sliding window are two closely related techniques that solve a large family of these problems in a single pass, in O(n) time and usually O(1) extra memory. They appear constantly in coding interviews and in real code that processes logs, streams and time series.
In this lesson we will learn both techniques with ten small problems, all tested in JavaScript. It follows the dynamic programming lesson and uses ideas from arrays and hash tables.
Part 1: Two Pointers
The idea is simple: instead of one index moving through the array, keep two indexes (pointers) and move them according to a rule. Each step moves at least one pointer, and neither ever moves backwards, so the whole scan takes O(n).
There are two common patterns:
- Opposite ends: one pointer starts at the beginning, the other at the end, and they move towards each other.
- Fast and slow: both start at the beginning, and one moves faster than the other.
1. Pair with a Target Sum (Opposite Ends):
Given a sorted array, find two numbers that add up to a target. The brute-force way tries every pair. With two pointers:
- If the sum is too small, move the left pointer right (to a bigger number).
- If the sum is too big, move the right pointer left (to a smaller number).
- If it matches, we’re done.
function pairWithSum(arr, target) {
let left = 0, right = arr.length - 1;
while (left < right) {
const sum = arr[left] + arr[right];
if (sum === target) return [left, right];
if (sum < target) left++;
else right--;
}
return null;
}
console.log(pairWithSum([1, 3, 4, 6, 8, 11], 10)); // [ 2, 3 ] (4 + 6)
Why is this safe? Because the array is sorted, when the sum is too small, the current left number can’t be part of any answer with an even smaller right number, so we can discard it for good. Every step throws away one candidate, which is why one pass is enough. (For an unsorted array, the hash table solution from the hash tables lesson is the better choice.)
2. Reverse an Array in Place:
function reverseInPlace(arr) {
let left = 0, right = arr.length - 1;
while (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
return arr;
}
console.log(reverseInPlace([1, 2, 3, 4, 5])); // [ 5, 4, 3, 2, 1 ]
3. Valid Palindrome:
Check whether a sentence reads the same forwards and backwards, ignoring spaces, punctuation and case. The pointers skip characters that aren’t letters or digits:
function isPalindrome(s) {
const ok = (c) => /[a-z0-9]/i.test(c);
let left = 0, right = s.length - 1;
while (left < right) {
if (!ok(s[left])) { left++; continue; }
if (!ok(s[right])) { right--; continue; }
if (s[left].toLowerCase() !== s[right].toLowerCase()) return false;
left++;
right--;
}
return true;
}
console.log(isPalindrome("A man, a plan, a canal: Panama")); // true
console.log(isPalindrome("race a car")); // false
Unlike the recursive version in the recursion lesson, this one uses O(1) extra memory: no new strings and no call stack.
4. Remove Duplicates from a Sorted Array (Fast and Slow):
Remove duplicates in place and return the number of unique values. The slow pointer marks the end of the unique part; the fast pointer scans ahead looking for the next new value:
function removeDuplicates(arr) {
if (arr.length === 0) return 0;
let slow = 0;
for (let fast = 1; fast < arr.length; fast++) {
if (arr[fast] !== arr[slow]) {
slow++;
arr[slow] = arr[fast];
}
}
return slow + 1;
}
const nums = [1, 1, 2, 3, 3, 3, 4];
const k = removeDuplicates(nums);
console.log(k, nums.slice(0, k)); // 4 [ 1, 2, 3, 4 ]
The fast/slow idea also detects a cycle in a linked list (Floyd’s “tortoise and hare” algorithm) and finds its middle node in one pass.
5. Merge Two Sorted Arrays:
One pointer in each array: always take the smaller of the two current elements. This is the “merge” step of merge sort from the sorting algorithms lesson.
function mergeSorted(a, b) {
const out = [];
let i = 0, j = 0;
while (i < a.length && j < b.length) out.push(a[i] <= b[j] ? a[i++] : b[j++]);
return out.concat(a.slice(i), b.slice(j));
}
console.log(mergeSorted([1, 4, 7], [2, 3, 8, 9])); // [ 1, 2, 3, 4, 7, 8, 9 ]
6. Container With Most Water:
Each number is the height of a vertical line. Pick two lines that, together with the x-axis, hold the most water. The amount is min(height) × distance.
Start with the widest container (both ends). Moving the taller line inwards can never help, because the width shrinks and the height is still limited by the shorter line. So always move the shorter one:
function maxArea(heights) {
let left = 0, right = heights.length - 1, best = 0;
while (left < right) {
const area = Math.min(heights[left], heights[right]) * (right - left);
best = Math.max(best, area);
if (heights[left] < heights[right]) left++;
else right--;
}
return best;
}
console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7])); // 49
This is a good example of the real skill behind two pointers: finding a rule that lets you safely discard options without checking them.
Part 2: Sliding Window
A sliding window is a special kind of two pointers where the two pointers mark the start and end of a contiguous range (a sub-array or substring). Instead of recomputing everything for each range, you update the result as the window slides: add the element entering on the right and remove the one leaving on the left.
7. Maximum Sum of k Consecutive Elements (Fixed Window):
A shop has daily sales figures. Which 3 consecutive days had the highest total? The brute-force way adds up every group of 3:
function maxSumBrute(arr, k) {
let best = -Infinity;
for (let i = 0; i + k <= arr.length; i++) {
let sum = 0;
for (let j = i; j < i + k; j++) sum += arr[j];
best = Math.max(best, sum);
}
return best;
}
But neighbouring windows share almost all their elements. When the window moves one step right, just add the new element and subtract the one that left:
function maxSumWindow(arr, k) {
let sum = 0;
for (let i = 0; i < k; i++) sum += arr[i]; // first window
let best = sum;
for (let i = k; i < arr.length; i++) {
sum += arr[i] - arr[i - k]; // slide: add new, remove old
best = Math.max(best, sum);
}
return best;
}
const sales = [200, 350, 100, 600, 450, 300, 50, 700];
console.log(maxSumBrute(sales, 3), maxSumWindow(sales, 3)); // 1350 1350
The brute-force version is O(n × k); the window version is O(n), no matter how big k is. On an array of 200,000 numbers with a window of 1,000, the brute-force version took about 224 ms on our test machine and the sliding window about 3 ms.
8. Longest Substring Without Repeating Characters (Variable Window):
In a variable-size window, the right pointer grows the window and the left pointer shrinks it whenever a rule is broken. Here the rule is “no character twice”. A Map remembers where each character was last seen, so when a repeat enters the window, the left pointer jumps just past its previous position:
function longestUniqueSubstring(s) {
const lastSeen = new Map();
let left = 0, best = 0, bestStart = 0;
for (let right = 0; right < s.length; right++) {
const ch = s[right];
if (lastSeen.has(ch) && lastSeen.get(ch) >= left) left = lastSeen.get(ch) + 1;
lastSeen.set(ch, right);
if (right - left + 1 > best) {
best = right - left + 1;
bestStart = left;
}
}
return s.slice(bestStart, bestStart + best);
}
console.log(longestUniqueSubstring("abcabcbb")); // abc
console.log(longestUniqueSubstring("pwwkew")); // wke
9. Smallest Sub-array with a Sum of at Least Target:
Here we want the shortest window. Grow the window until it is valid (sum ≥ target), then shrink it from the left as long as it stays valid, recording the length each time:
function minSubarrayLen(target, arr) {
let left = 0, sum = 0, best = Infinity;
for (let right = 0; right < arr.length; right++) {
sum += arr[right];
while (sum >= target) {
best = Math.min(best, right - left + 1);
sum -= arr[left];
left++;
}
}
return best === Infinity ? 0 : best;
}
console.log(minSubarrayLen(7, [2, 3, 1, 2, 4, 3])); // 2 ([4, 3])
Even though there is a while loop inside the for loop, this is still O(n): each element is added once and removed at most once. (This trick only works when all numbers are positive, so that growing the window always increases the sum.)
10. Counting Anagrams of a Pattern:
How many substrings of text are anagrams of pattern? Use a fixed window of the pattern’s length and keep character counts in a Map, updating them as the window slides:
function countAnagrams(text, pattern) {
const need = new Map();
for (const c of pattern) need.set(c, (need.get(c) || 0) + 1);
const window = new Map();
const k = pattern.length;
const matches = () => [...need].every(([c, n]) => window.get(c) === n);
let count = 0;
for (let i = 0; i < text.length; i++) {
window.set(text[i], (window.get(text[i]) || 0) + 1); // add new
if (i >= k) window.set(text[i - k], window.get(text[i - k]) - 1); // remove old
if (i >= k - 1 && matches()) count++;
}
return count;
}
console.log(countAnagrams("cbaebabacd", "abc")); // 2 ("cba" and "bac")
How to Recognise Which Technique to Use
- The array is sorted, and you’re looking for a pair or triplet with some property: two pointers from opposite ends.
- You must modify an array in place, or work with a linked list: fast and slow pointers.
- The problem says “consecutive”, “contiguous”, “substring” or “sub-array”, and asks for a maximum, minimum, longest, shortest or count: sliding window.
- The window size is given (
kdays, a pattern’s length): fixed window. The size depends on a condition: variable window (grow with the right pointer, shrink with the left).
Complexity
- Time: O(n) for every example above, because each pointer only moves forward and crosses the array at most once.
- Space: O(1) for the pure pointer problems; O(k) or O(size of the alphabet) when the window keeps a
Mapof counts.
Where These Techniques Are Used
- Analytics and monitoring: moving averages, “requests in the last 60 seconds”, and the sliding-window rate limiters from the rate limiting lesson.
- Networking: TCP uses a sliding window to control how much data can be in flight.
- Databases and big data: merging sorted runs of data (merge join, external sorting).
- Text processing: searching for patterns and anagrams in large documents.
Conclusion:
Two pointers and sliding windows replace nested loops with a single pass. Opposite-end pointers work on sorted data by discarding candidates that can’t be the answer; fast and slow pointers handle in-place updates and linked lists; and sliding windows process contiguous ranges by adding the element that enters and removing the one that leaves. Look for the clues (sorted input, “pair”, “contiguous”, “substring”, “longest” or “shortest”) and you will often find an O(n) solution where the obvious one is O(n²).
In the next DSA lesson we will learn about tries (prefix trees), the data structure behind autocomplete and spell checkers.


