1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Two Pointers Pattern
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
16Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Two Pointers Pattern

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
16Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Two Pointers Pattern

Overview

The Two Pointers pattern is a highly efficient algorithmic technique used primarily on arrays and strings. Instead of using a single loop variable (i) or nested loops (i and j testing every combination), you use two integer variables that act as 'pointers' to different indices in the data.

The most classic variation is Opposite Direction pointers: one pointer starts at the beginning (left = 0) and one starts at the end (right = arr.length - 1). They move towards each other until they meet. This is the foundation of algorithms for reversing strings, checking palindromes, and solving 'Two Sum' on sorted arrays.

The second variation is Same Direction pointers (often called 'Fast and Slow' pointers), where both start at 0 but move at different speeds.

The beauty of this pattern is that it almost always reduces an O(N^2) naive nested-loop solution into a blazing fast O(N) solution.

Syntax

Reversing an Array In-Place
java
public class TwoPointers {
    // 1. Opposite Direction Pattern
    public static void reverseArray(int[] arr) {
        int left = 0;
        int right = arr.length - 1;
        
        // Loop runs until the pointers crash into each other
        while (left < right) {
            // Swap the elements at the pointers
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            
            // Move pointers inward!
            left++;
            right--;
        }
    }
    
    // 2. Finding a Target Sum in a SORTED Array (Two Sum II)
    public static boolean hasTargetSum(int[] sortedArr, int target) {
        int left = 0;
        int right = sortedArr.length - 1;
        
        while (left < right) {
            int currentSum = sortedArr[left] + sortedArr[right];
            
            if (currentSum == target) {
                return true; // Found the pair!
            } else if (currentSum < target) {
                // Sum is too small. We need a bigger number.
                // Since array is sorted, moving left pointer to the right increases sum.
                left++; 
            } else {
                // Sum is too big. We need a smaller number.
                right--; 
            }
        }
        return false;
    }
}

Common Pitfalls

  • Using left <= right when swapping elements. If you use <= in an array reversal, when left == right (the middle element of an odd-length array), the algorithm swaps the element with itself. While harmless, it's an unnecessary operation. left < right is cleaner.
  • Applying the Two Sum pointer logic to an UNSORTED array. The logic if (sum < target) left++ strictly relies on the array being sorted in ascending order. If the array is unsorted, moving the left pointer doesn't guarantee a larger number. For unsorted arrays, you must use a HashMap instead.
  • Infinite loops due to forgotten increments. If you use a while loop and forget to write left++ or right-- in one of your if-else branches, the pointers will never move, freezing the program.

Interview Questions

How do you check if a String is a Palindrome using Two Pointers?

Initialize left at 0 and right at str.length() - 1. While left < right, check if str.charAt(left) == str.charAt(right). If they don't match, return false immediately. Otherwise, left++ and right--. If the loop finishes, return true. This takes O(N) time and O(1) space.

What is the 'Fast and Slow Pointers' pattern?

Also known as the Tortoise and Hare algorithm. It uses two pointers moving in the same direction at different speeds. It is famous for detecting cycles in a Linked List (if the fast pointer laps the slow pointer, a cycle exists) or finding the middle of a Linked List in one pass.

Real-World Example

When analyzing sensor telemetry data (like temperatures sorted by time), if an engineer wants to find two specific timestamps where the combined temperature difference exactly matches a specific threshold, a two-pointer approach sweeps through the millions of data points in linear time instantly.

example
java
// Check if a word is a palindrome, ignoring non-alphanumeric chars
public boolean isPalindrome(String s) {
    int i = 0, j = s.length() - 1;
    while (i < j) {
        while (i < j && !Character.isLetterOrDigit(s.charAt(i))) i++;
        while (i < j && !Character.isLetterOrDigit(s.charAt(j))) j--;
        
        if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) {
            return false;
        }
        i++; j--;
    }
    return true;
}

Check Your Knowledge

Test your understanding of Two Pointers Pattern with these quick questions.

Question 1

What is the primary benefit of the Two Pointers pattern?

Question 2

When using Two Pointers to find a target sum (Two Sum), what MUST be true about the array?

Question 3

In the opposite direction pattern, what is the standard while loop condition?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Two Pointers Pattern

Overview

The Two Pointers pattern is a highly efficient algorithmic technique used primarily on arrays and strings. Instead of using a single loop variable (i) or nested loops (i and j testing every combination), you use two integer variables that act as 'pointers' to different indices in the data.

The most classic variation is Opposite Direction pointers: one pointer starts at the beginning (left = 0) and one starts at the end (right = arr.length - 1). They move towards each other until they meet. This is the foundation of algorithms for reversing strings, checking palindromes, and solving 'Two Sum' on sorted arrays.

The second variation is Same Direction pointers (often called 'Fast and Slow' pointers), where both start at 0 but move at different speeds.

The beauty of this pattern is that it almost always reduces an O(N^2) naive nested-loop solution into a blazing fast O(N) solution.

Syntax

Reversing an Array In-Place
java
public class TwoPointers {
    // 1. Opposite Direction Pattern
    public static void reverseArray(int[] arr) {
        int left = 0;
        int right = arr.length - 1;
        
        // Loop runs until the pointers crash into each other
        while (left < right) {
            // Swap the elements at the pointers
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            
            // Move pointers inward!
            left++;
            right--;
        }
    }
    
    // 2. Finding a Target Sum in a SORTED Array (Two Sum II)
    public static boolean hasTargetSum(int[] sortedArr, int target) {
        int left = 0;
        int right = sortedArr.length - 1;
        
        while (left < right) {
            int currentSum = sortedArr[left] + sortedArr[right];
            
            if (currentSum == target) {
                return true; // Found the pair!
            } else if (currentSum < target) {
                // Sum is too small. We need a bigger number.
                // Since array is sorted, moving left pointer to the right increases sum.
                left++; 
            } else {
                // Sum is too big. We need a smaller number.
                right--; 
            }
        }
        return false;
    }
}

Common Pitfalls

  • Using left <= right when swapping elements. If you use <= in an array reversal, when left == right (the middle element of an odd-length array), the algorithm swaps the element with itself. While harmless, it's an unnecessary operation. left < right is cleaner.
  • Applying the Two Sum pointer logic to an UNSORTED array. The logic if (sum < target) left++ strictly relies on the array being sorted in ascending order. If the array is unsorted, moving the left pointer doesn't guarantee a larger number. For unsorted arrays, you must use a HashMap instead.
  • Infinite loops due to forgotten increments. If you use a while loop and forget to write left++ or right-- in one of your if-else branches, the pointers will never move, freezing the program.

Interview Questions

How do you check if a String is a Palindrome using Two Pointers?

Initialize left at 0 and right at str.length() - 1. While left < right, check if str.charAt(left) == str.charAt(right). If they don't match, return false immediately. Otherwise, left++ and right--. If the loop finishes, return true. This takes O(N) time and O(1) space.

What is the 'Fast and Slow Pointers' pattern?

Also known as the Tortoise and Hare algorithm. It uses two pointers moving in the same direction at different speeds. It is famous for detecting cycles in a Linked List (if the fast pointer laps the slow pointer, a cycle exists) or finding the middle of a Linked List in one pass.

Real-World Example

When analyzing sensor telemetry data (like temperatures sorted by time), if an engineer wants to find two specific timestamps where the combined temperature difference exactly matches a specific threshold, a two-pointer approach sweeps through the millions of data points in linear time instantly.

example
java
// Check if a word is a palindrome, ignoring non-alphanumeric chars
public boolean isPalindrome(String s) {
    int i = 0, j = s.length() - 1;
    while (i < j) {
        while (i < j && !Character.isLetterOrDigit(s.charAt(i))) i++;
        while (i < j && !Character.isLetterOrDigit(s.charAt(j))) j--;
        
        if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) {
            return false;
        }
        i++; j--;
    }
    return true;
}

Check Your Knowledge

Test your understanding of Two Pointers Pattern with these quick questions.

Question 1

What is the primary benefit of the Two Pointers pattern?

Question 2

When using Two Pointers to find a target sum (Two Sum), what MUST be true about the array?

Question 3

In the opposite direction pattern, what is the standard while loop condition?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A