DEV Community

Dev Cookies
Dev Cookies

Posted on

๐Ÿƒโ€โ™‚๏ธ๐Ÿƒโ€โ™€๏ธ Two Pointer Technique in Java โ€“ The Ultimate Guide with Examples

The Two Pointer technique is one of the most intuitive yet powerful problem-solving strategies used in competitive programming and system design questions involving arrays, strings, and linked lists.

In this blog, weโ€™ll break it down step by step with examples, Java code, and interview patterns.


๐Ÿง  What is the Two Pointer Technique?

The idea is simple:

Use two pointers (indices) to iterate through a data structure โ€” usually starting from either end or both ends โ€” and move them based on conditions to optimize the solution.


๐Ÿ”ฅ When to Use It?

  • When the problem asks for pairs or subarrays meeting a condition
  • To reduce nested loops (O(nยฒ) โ†’ O(n))
  • Works best on sorted arrays or strings

โœจ Common Two Pointer Patterns

Pattern Use Case
Opposite Ends Sorted arrays, pairs with sum
Sliding Window Longest substring, subarrays
Same Direction Merge sorted arrays, duplicates

๐Ÿงช Java Examples

๐Ÿ“˜ 1. Two Sum โ€“ Sorted Array

๐Ÿ”ง Find two numbers that sum up to a target.

public int[] twoSumSorted(int[] nums, int target) {
    int left = 0, right = nums.length - 1;

    while (left < right) {
        int sum = nums[left] + nums[right];

        if (sum == target)
            return new int[]{left, right};
        else if (sum < target)
            left++;
        else
            right--;
    }
    return new int[]{-1, -1};
}
Enter fullscreen mode Exit fullscreen mode

โฑ Time: O(n)


๐Ÿ“˜ 2. Reverse a String

public void reverseString(char[] s) {
    int left = 0, right = s.length - 1;

    while (left < right) {
        char temp = s[left];
        s[left++] = s[right];
        s[right--] = temp;
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“˜ 3. Remove Duplicates from Sorted Array

public int removeDuplicates(int[] nums) {
    int i = 0;

    for (int j = 1; j < nums.length; j++) {
        if (nums[i] != nums[j]) {
            i++;
            nums[i] = nums[j];
        }
    }
    return i + 1;
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿง  Here i is slow pointer and j is fast pointer.


๐Ÿ“˜ 4. Move Zeroes to End

public void moveZeroes(int[] nums) {
    int insertPos = 0;

    for (int num : nums) {
        if (num != 0) {
            nums[insertPos++] = num;
        }
    }

    while (insertPos < nums.length) {
        nums[insertPos++] = 0;
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“˜ 5. Container With Most Water

๐Ÿ”ง Find the maximum area of water that can be contained between two lines.

public int maxArea(int[] height) {
    int left = 0, right = height.length - 1, max = 0;

    while (left < right) {
        int h = Math.min(height[left], height[right]);
        int area = h * (right - left);
        max = Math.max(max, area);

        if (height[left] < height[right]) left++;
        else right--;
    }
    return max;
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“˜ 6. Is Palindrome?

public boolean isPalindrome(String s) {
    int left = 0, right = s.length() - 1;

    while (left < right) {
        if (s.charAt(left) != s.charAt(right))
            return false;
        left++;
        right--;
    }
    return true;
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ก Trickier Problems You Can Solve

Problem Idea
3Sum Sort + fix one + two-pointer
Longest Substring Without Repeating Characters Sliding window (variant)
Merge Intervals Same direction pointers
Dutch National Flag Three pointers

๐Ÿงฎ Comparison Table

Approach Time Complexity Space Complexity
Brute-force O(nยฒ) O(1)
Two Pointers O(n) O(1)

โœ… Key Takeaways

  • Two pointers help optimize brute-force O(nยฒ) approaches to O(n).
  • Works great on sorted arrays, strings, and linked lists.
  • Variants include sliding window, fast-slow pointers, and three pointers.

๐ŸŽฏ Final Words

Mastering the Two Pointer technique will level up your coding game โ€” especially in interviews. Pair it with other concepts like sorting, hash maps, and prefix sums for explosive problem-solving combos.


Top comments (0)