DEV Community

Cover image for ⚡ Two Pointer Technique
Mohammed mhanna
Mohammed mhanna

Posted on

⚡ Two Pointer Technique

Ever spent hours writing nested loops to solve simple array or string problems, only to feel it’s slow and messy?

The Two Pointer Technique is a game-changer. It’s a powerful strategy to traverse arrays, lists, or strings efficiently using two markers (pointers), reducing time complexity and improving code readability.

By the end of this post, you’ll know:

What the Two Pointer Technique is

How it works step by step

Real-world examples in Java

Common pitfalls to avoid

Practice challenges to master it


🌱 What Is the Two Pointer Technique?

The Two Pointer Technique uses two indices to iterate over data structures:

Opposite ends: One pointer at the start, one at the end

Same start: Slow and fast pointers moving at different speeds

✅ Ideal for sorted arrays, strings, and problems that require comparison or condition checking.


🛠 How It Works: Step by Step
1️⃣ Opposite Ends

Move pointers toward each other based on conditions.

Common for: finding pairs with a target sum, checking palindromes.

2️⃣ Same End (Slow & Fast)

Slow pointer moves step by step

Fast pointer moves faster

Detect duplicates, cycles in lists, or sliding window problems

3️⃣ Adjust Pointers Dynamically

If current condition < target → move left/slow forward

If current condition > target → move right/fast backward

Stop when pointers meet or satisfy problem condition


💡 Examples in Java
Example 1: Reverse an Array

int left = 0, right = arr.length - 1;
while(left < right){
    int temp = arr[left];
    arr[left] = arr[right];
    arr[right] = temp;
    left++; right--;
}
Enter fullscreen mode Exit fullscreen mode

✅ Enforcement: In-place reversal saves memory and time.


Example 2: Pair With Target Sum

int left = 0, right = arr.length - 1;
while(left < right){
    int sum = arr[left] + arr[right];
    if(sum == target){ System.out.println(arr[left] + ", " + arr[right]); break; }
    else if(sum < target) left++; else right--;
}
Enter fullscreen mode Exit fullscreen mode

✅ Enforcement: Linear time solution instead of nested loops.


Example 3: Remove Duplicates from Sorted Array

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

✅ Enforcement: In-place modification reduces memory usage.


🌍 Real-World Applications

Palindrome check in strings

Two-sum problems in finance, scoring apps

Sliding window problems: max/min in a range

Cycle detection in linked lists


⚠️ Common Pitfalls & Mistakes

❌ Using Two Pointers on unsorted arrays without sorting first

❌ Moving pointers incorrectly → infinite loops or missed elements

❌ Using nested loops when two pointers suffice

❌ Ignoring boundary conditions (array length, empty arrays)

✅ Tip: Always visualize the pointer movement before coding.


🧩 Practice Challenges

Check if a string is a palindrome using two pointers.

Merge two sorted arrays efficiently.

Find all triplets in an array with a given sum.

Detect a cycle in a linked list (slow & fast pointers).

Sliding window: Find max sum of size k subarrays.


📚 Resources to Level Up

GeeksforGeeks: Two Pointer Technique

LeetCode: Two Pointer Problems

Java Arrays & Collections


🎯 Takeaway

The Two Pointer Technique is your secret weapon for solving array and string problems efficiently. It improves performance, reduces complexity, and makes your code cleaner and more readable.

💬 Engagement Questions:

Which problem did two pointers help you solve the most?

Can you think of a scenario where this technique would save time in your project?

Have you tried slow & fast pointers for linked lists yet?

Drop your thoughts in the comments — let’s discuss and learn together! 🚀

Top comments (0)