← Back to All Patterns

Two Pointers Pattern

šŸŽÆ Explain Like I'm 5...

Imagine you have a row of 10 toy blocks numbered 1 to 10. You want to find two blocks that add up to 11!

šŸ§’ Kid's Way (Slow): Pick block 1, then check it with ALL other blocks (1+2, 1+3, 1+4...). Then pick block 2 and check with all others (2+3, 2+4...). This takes FOREVER! 😓

šŸ§™ Smart Way (Two Pointers): Put your LEFT hand šŸ‘ˆ on block 1 and RIGHT hand šŸ‘‰ on block 10.

  • • Add them: 1 + 10 = 11 → Found it! šŸŽ‰
  • • If sum is too small, move LEFT hand right →
  • • If sum is too big, move RIGHT hand left ←

šŸš€ Why is it faster? Instead of checking EVERY pair (45 checks!), we only move our hands closer until we find the answer. Much smarter! It's like having two helpers working together instead of one person doing all the work alone.

šŸŽØ See It In Action!

Below you'll find interactive animations for each example. Use the controls to play, pause, and step through each algorithm!

ā–¶ Play/Pause
ā­ Step Forward
šŸ”„ Reset

When Should You Use This Pattern?

  • āœ“The array or string is sorted (or you can sort it)
  • āœ“You need to find a pair of numbers
  • āœ“You want to check if something is a palindrome
  • āœ“You need to remove duplicates

šŸ“ Example 1: Find Two Numbers That Add Up to Target

Let's say you have a sorted array: [1, 2, 3, 4, 6] and you want to find two numbers that add up to 6.

šŸŽ¬ Two Sum - Finding pairs that add to target

Target: 6Current Sum: 7
šŸ‘ˆ Left
1
[0]
2
[1]
3
[2]
4
[3]
Right šŸ‘‰
6
[4]

1 + 6 = 7 (too big, move right pointer left)

Step 1 of 333%
Left Pointer
Right Pointer
Match/Complete

Step-by-Step Thinking:

  1. Put one pointer at the start (left = 0), one at the end (right = 4)
  2. Add the numbers at both pointers: 1 + 6 = 7 (too big!)
  3. Move the right pointer left: 1 + 4 = 5 (too small!)
  4. Move the left pointer right: 2 + 4 = 6 (Perfect! āœ“)
TwoSum.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class TwoSum {
// Function to find two numbers that add up to target
public static int[] findPair(int[] arr, int target) {
// Start with two pointers
int left = 0; // šŸ‘ˆ starts at beginning
int right = arr.length - 1; // šŸ‘‰ starts at end
// Keep going until pointers meet
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == target) {
// Found it! Return the pair
return new int[]{arr[left], arr[right]};
}
else if (sum < target) {
// Sum too small, move left pointer right
left++;
}
else {
// Sum too big, move right pointer left
right--;
}
}
// No pair found
return new int[]{-1, -1};
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 6};
int target = 6;
int[] result = findPair(arr, target);
System.out.println("Pair: " + result[0] + " + " + result[1]);
// Output: Pair: 2 + 4
}
}

šŸ“ Example 2: Check if String is a Palindrome

A palindrome reads the same forwards and backwards, like "racecar" or "mom".

šŸŽ¬ Palindrome Check - Comparing from both ends

šŸ‘ˆ Left
r
[0]
a
[1]
c
[2]
e
[3]
c
[4]
a
[5]
Right šŸ‘‰
r
[6]

Compare 'r' and 'r' - match! Continue...

Step 1 of 425%
Left Pointer
Right Pointer
Match/Complete
Palindrome.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Palindrome {
public static boolean isPalindrome(String str) {
// Remove spaces and convert to lowercase
str = str.toLowerCase().replaceAll(" ", "");
int left = 0; // šŸ‘ˆ starts at beginning
int right = str.length() - 1; // šŸ‘‰ starts at end
while (left < right) {
// Compare characters at both pointers
if (str.charAt(left) != str.charAt(right)) {
return false; // Not matching = not palindrome
}
// Move both pointers towards center
left++;
right--;
}
return true; // All characters matched!
}
public static void main(String[] args) {
System.out.println(isPalindrome("racecar")); // true
System.out.println(isPalindrome("hello")); // false
System.out.println(isPalindrome("A man a plan a canal Panama")); // true
}
}

šŸ“ Example 3: Remove Duplicates from Sorted Array

Given [1, 1, 2, 2, 3, 4, 4], remove duplicates to get [1, 2, 3, 4].

šŸŽ¬ Remove Duplicates - Using slow and fast pointers

šŸ‘ˆ Slow
1
[0]
Fast šŸ‘‰
1
[1]
2
[2]
2
[3]
3
[4]
4
[5]
4
[6]

1 == 1 (duplicate, only fast moves)

Step 1 of 714%
Slow Pointer
Fast Pointer
Match/Complete
RemoveDuplicates.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class RemoveDuplicates {
public static int removeDuplicates(int[] arr) {
if (arr.length == 0) return 0;
int slow = 0; // Points to last unique element
// Fast pointer explores the array
for (int fast = 1; fast < arr.length; fast++) {
// Found a new unique element?
if (arr[fast] != arr[slow]) {
slow++; // Move slow pointer
arr[slow] = arr[fast]; // Place unique element
}
}
return slow + 1; // Number of unique elements
}
public static void main(String[] args) {
int[] arr = {1, 1, 2, 2, 3, 4, 4};
int uniqueCount = removeDuplicates(arr);
System.out.print("Unique elements: ");
for (int i = 0; i < uniqueCount; i++) {
System.out.print(arr[i] + " ");
}
// Output: Unique elements: 1 2 3 4
}
}

šŸ”‘ Key Points to Remember

  • 1ļøāƒ£Two pointers help you avoid nested loops (faster than O(n²)!)
  • 2ļøāƒ£Usually works best with sorted arrays
  • 3ļøāƒ£Time Complexity: O(n) - you only go through the array once!
  • 4ļøāƒ£Space Complexity: O(1) - you only use two variables!

šŸ’Ŗ Practice Problems

  • • Container With Most Water
  • • 3Sum Problem
  • • Sort Colors (Dutch National Flag)
  • • Trapping Rain Water
  • • Remove Element