---
title: "Two Pointers and Sliding Window Techniques"
url: https://www.khanwaseem.com/blog/data-structure-and-algorithm/two-pointers-and-sliding-window
author: "khan Waseem"
published: 2026-11-27
updated: 2026-11-27
topics: ["Data Structure and Algorithm", "Blog"]
description: "Two simple techniques that turn many O(n²) array and string problems into O(n): opposite-end and fast/slow two pointers, and fixed and variable-size sliding windows, with ten tested JavaScript examples and a guide to…"
---

# Two Pointers and Sliding Window Techniques

Table of Contents

[Toggle](#)

- [Introduction:](#introduction)
- [Part 1: Two Pointers](#part-1-two-pointers)[1. Pair with a Target Sum (Opposite Ends):](#1-pair-with-a-target-sum-opposite-ends)
- [2. Reverse an Array in Place:](#2-reverse-an-array-in-place)
- [3. Valid Palindrome:](#3-valid-palindrome)
- [4. Remove Duplicates from a Sorted Array (Fast and Slow):](#4-remove-duplicates-from-a-sorted-array-fast-and-slow)
- [5. Merge Two Sorted Arrays:](#5-merge-two-sorted-arrays)
- [6. Container With Most Water:](#6-container-with-most-water)

- [Part 2: Sliding Window](#part-2-sliding-window)[7. Maximum Sum of k Consecutive Elements (Fixed Window):](#7-maximum-sum-of-k-consecutive-elements-fixed-window)
- [8. Longest Substring Without Repeating Characters (Variable Window):](#8-longest-substring-without-repeating-characters-variable-window)
- [9. Smallest Sub-array with a Sum of at Least Target:](#9-smallest-sub-array-with-a-sum-of-at-least-target)
- [10. Counting Anagrams of a Pattern:](#10-counting-anagrams-of-a-pattern)

- [How to Recognise Which Technique to Use](#how-to-recognise-which-technique-to-use)
- [Complexity](#complexity)
- [Where These Techniques Are Used](#where-these-techniques-are-used)
- [Conclusion:](#conclusion)

## 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](https://blog.khanwaseem.com/dynamic-programming/) lesson and uses ideas from [arrays](https://blog.khanwaseem.com/array-data-structure/) and [hash tables](https://blog.khanwaseem.com/hash-table-data-structure/).

## 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.

```javascript
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)Code language: JavaScript (javascript)
```

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:

```javascript
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 ]Code language: JavaScript (javascript)
```

### 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:

```javascript
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"));                     // falseCode language: JavaScript (javascript)
```

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:

```javascript
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 ]Code language: JavaScript (javascript)
```

The fast/slow idea also detects a cycle in a [linked list](https://blog.khanwaseem.com/linked-list-data-structure/) (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](https://blog.khanwaseem.com/sorting-algorithms/) lesson.

```javascript
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 ]Code language: JavaScript (javascript)
```

### 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:

```javascript
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])); // 49Code language: JavaScript (javascript)
```

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:

```javascript
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;
}Code language: JavaScript (javascript)
```

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:

```javascript
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 1350Code language: JavaScript (javascript)
```

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:

```javascript
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"));   // wkeCode language: JavaScript (javascript)
```

### 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:

```javascript
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])Code language: JavaScript (javascript)
```

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:

```javascript
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")Code language: JavaScript (javascript)
```

## 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 (`k` days, 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 `Map` of 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](https://blog.khanwaseem.com/what-is-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.

### Related posts:

[What Is Rate Limiting? Algorithms and Design](https://blog.khanwaseem.com/what-is-rate-limiting/)
[Heap Sort](https://blog.khanwaseem.com/heap-sort/)
[Recursion Explained with Examples](https://blog.khanwaseem.com/recursion-in-data-structures-and-algorithms/)
[Dynamic Programming for Beginners](https://blog.khanwaseem.com/dynamic-programming/)

Powered by [YARPP](https://yarpp.com).
