Chaturmind
LearnDSASystem DesignBlogPremium
Sign inGet started
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML

Company

  • Blog
  • Premium
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Arrays & Strings Mastery

Core Patterns

  • Two Pointers Pattern
  • Sliding Window Pattern
  • Prefix Sums

String Problems

  • String Hashing & Anagrams
  • String Two-Pointer Problems
Chaturmind
← Arrays & Strings Mastery

Core Patterns

  • Two Pointers Pattern
  • Sliding Window Pattern
  • Prefix Sums

String Problems

  • String Hashing & Anagrams
  • String Two-Pointer Problems
HomeLearnDSAArrays & Strings MasteryCore Patterns
✓ FreeBeginner· 12 min read

Two Pointers Pattern

Solve O(n²) problems in O(n) — the two-pointer technique and when to apply it.

Published March 10, 2025


Two Pointers Pattern

The two-pointer technique uses two indices that move through an array (or string) to avoid nested loops — turning O(n²) into O(n).

When to use it

  • Array is sorted (or can be sorted)
  • Looking for a pair/triplet that satisfies a condition
  • Palindrome check
  • Merging two sorted arrays

Template 1: Opposite ends

// Check if a sorted array has a pair summing to target
public boolean hasPairSum(int[] nums, int target) {
    int left = 0, right = nums.length - 1;
    while (left < right) {
        int sum = nums[left] + nums[right];
        if (sum == target) return true;
        if (sum < target)  left++;   // need larger sum → move left pointer right
        else               right--;  // need smaller sum → move right pointer left
    }
    return false;
}

Template 2: Same direction (fast and slow)

// Remove duplicates from sorted array in-place
public int removeDuplicates(int[] nums) {
    int slow = 0;
    for (int fast = 1; fast < nums.length; fast++) {
        if (nums[fast] != nums[slow]) {
            slow++;
            nums[slow] = nums[fast];
        }
    }
    return slow + 1;
}

Classic Problems

ProblemStrategy
Two Sum (sorted array)Opposite ends
3SumFix first, opposite ends for rest
Container With Most WaterOpposite ends, move shorter side
Valid PalindromeOpposite ends
Remove DuplicatesSlow/fast same direction
Merge Sorted ArraysTwo arrays, two pointers

Interview Tip

When you see a sorted array + pair/triplet problem, immediately think two pointers. The key insight: in a sorted array, moving left right increases the sum; moving right left decreases it. This guarantees you find the answer without missing any pair.

Next

Sliding Window Pattern

AI Tutor

Lesson: Two Pointers Pattern

Quick actions

AI responses can be inaccurate. Verify critical information.