Problem-Solving March 21, 2026 14 min read 3 views

Common Two Pointer Problems on LeetCode | Step-by-Step Guide

Master the most common two pointer problems on LeetCode with this comprehensive guide. Learn pattern recognition, step-by-step solutions, and optimization techniques to solve array and string problems efficiently.

Table of Contents

Solving Common Two Pointer Problems on LeetCode: A Step-by-Step Guide

The two-pointer technique is one of the most versatile and frequently tested patterns in coding interviews. When you start solving common two pointer problems on LeetCode, you’ll quickly notice that this elegant approach can transform O(n²) brute-force solutions into clean O(n) algorithms.

In this comprehensive guide, we’ll walk through the most common two pointer problems on LeetCode, breaking down each solution step-by-step. Whether you’re preparing for technical interviews or looking to strengthen your algorithm skills, mastering these problems will give you a significant edge in your coding journey.

If you’re new to the technique, we recommend first checking out our detailed guide on the Two Pointer Technique | Master Array Problems in 8 Steps before diving into these LeetCode solutions.

Understanding the Two Pointer Technique

Before we tackle specific problems, let’s quickly review what makes the two-pointer technique so powerful. The approach involves using two pointers that traverse a data structure—typically an array or string—in a coordinated manner to solve problems efficiently.

When to Use Two Pointers

You’ll find yourself reaching for this technique when:

  • Working with sorted arrays (like in Two Sum II or 3Sum)
  • Dealing with palindrome checking (Valid Palindrome)
  • Removing duplicates in-place (Remove Duplicates from Sorted Array)
  • Merging sorted arrays
  • Finding pairs or triplets that satisfy certain conditions
    The beauty of this approach lies in its efficiency. Instead of nested loops that lead to O(n²) time complexity, two pointers often achieve O(n) or O(n log n) solutions. For a deeper understanding of why this matters, check out our article on Brute Force vs Optimal Solutions | Algorithm Optimization Guide.

Problem 1: Two Sum II - Input Array Is Sorted (LeetCode 167)

This is perhaps the most fundamental of all common two pointer problems on LeetCode. The problem states: Given a 1-indexed sorted array of integers and a target, find two numbers that add up to the target and return their indices.

Problem Analysis

Input: numbers = [2,7,11,15], target = 9
Output: [1,2] (because 2 + 7 = 9)

The key constraint is that the array is already sorted in ascending order. This is crucial because it allows us to use the two-pointer technique effectively.

The Two-Pointer Solution

 

Python

def twoSum(self, numbers, target):
    left, right = 0, len(numbers) - 1

    while left < right:
        current_sum = numbers[left] + numbers[right]

        if current_sum == target:
            return [left + 1, right + 1]  # 1-indexed return
        elif current_sum < target:
            left += 1  # Need a larger sum, move left pointer right
        else:
            right -= 1  # Need a smaller sum, move right pointer left

    return []  # No solution found

 

Step-by-Step Walkthrough

  1. Initialize pointers: left at the beginning (index 0) and right at the end (index 3)
  2. Calculate sum: 2 + 15 = 17, which is greater than target 9
  3. Adjust pointers: Since sum is too large, decrement right to 11
  4. New sum: 2 + 11 = 13, still too large, decrement right to 7
  5. Match found: 2 + 7 = 9, return indices [1, 2]

Time and Space Complexity

  • Time Complexity: O(n) - we traverse the array at most once
  • Space Complexity: O(1) - we only use two pointers, no extra space
     

This solution elegantly demonstrates why the two-pointer technique is preferred over using a hash map when the array is sorted. For a refresher on analyzing algorithm efficiency, see our guide on Understanding Time Complexity in Python.

Problem 2: Valid Palindrome (LeetCode 125)

A palindrome is a string that reads the same forward and backward. This classic problem tests your ability to clean and compare strings efficiently.

Problem Analysis

Input: s = “A man, a plan, a canal: Panama”
Output: true (after ignoring non-alphanumeric characters and case)

The challenge here is handling non-alphanumeric characters and case insensitivity while checking if the string is a palindrome.

The Two-Pointer Solution

 

Python

def isPalindrome(self, s):
    left, right = 0, len(s) - 1

    while left < right:
        # Move left pointer to next alphanumeric character
        while left < right and not s[left].isalnum():
            left += 1
        # Move right pointer to previous alphanumeric character
        while left < right and not s[right].isalnum():
            right -= 1

        # Compare characters (case insensitive)
        if s[left].lower() != s[right].lower():
            return False

        left += 1
        right -= 1

    return True


 

Key Insights

This solution demonstrates an important pattern in common two pointer problems on LeetCode: the pointers don’t always move simultaneously. Here, they move independently to skip non-alphanumeric characters:

  • The left pointer advances until it finds a valid character
  • The right pointer retreats until it finds a valid character
  • Only then do we compare and move both pointers

Alternative Approach: Cleaning First

While the above solution is efficient, some developers prefer to clean the string first:

 

Python

def isPalindrome(self, s):
    # Clean the string: keep only alphanumeric, lowercase
    cleaned = ''.join(c.lower() for c in s if c.isalnum())
    left, right = 0, len(cleaned) - 1

    while left < right:
        if cleaned[left] != cleaned[right]:
            return False
        left += 1
        right -= 1

    return True

 

This approach is more readable but uses O(n) extra space. For large strings, the in-place version is preferable.

Problem 3: Remove Duplicates from Sorted Array (LeetCode 26)

This problem tests your ability to modify an array in-place while maintaining the relative order of elements—a common requirement in coding interviews.

Problem Analysis

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, with the first five elements being [0,1,2,3,4]

We need to return the new length after removing duplicates, and the array should be modified in-place so that the first k elements contain the unique values.

The Two-Pointer Solution

 

Python

def removeDuplicates(self, nums):
    if not nums:
        return 0

    # Slow pointer: points to the last unique element
    slow = 0

    # Fast pointer: explores the array
    for fast in range(1, len(nums)):
        if nums[fast] != nums[slow]:
            slow += 1
            nums[slow] = nums[fast]

    return slow + 1  # +1 because slow is 0-indexed

 

Understanding the Pattern

This solution introduces a common variant: the slow and fast pointer pattern:

  • The slow pointer (also called the writer) marks where the next unique element should go
  • The fast pointer (reader) scans ahead to find new unique elements
  • When a new unique value is found, we increment the slow pointer and copy the value
    This pattern appears frequently in common two pointer problems on LeetCode, particularly those involving in-place array modifications.

Problem 4: 3Sum (LeetCode 15)

The 3Sum problem is where things get interesting. It’s a classic example of how the two-pointer technique can be extended to solve more complex problems.

Problem Analysis

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]

We need to find all unique triplets that sum to zero. The challenge lies in handling duplicates efficiently while maintaining O(n²) time complexity.

The Solution

 

Python

def threeSum(self, nums):
    result = []
    nums.sort()  # Sorting is crucial for the two-pointer approach

    for i in range(len(nums) - 2):
        # Skip duplicate values for the first element
        if i > 0 and nums[i] == nums[i-1]:
            continue

        left, right = i + 1, len(nums) - 1

        while left < right:
            current_sum = nums[i] + nums[left] + nums[right]

            if current_sum == 0:
                result.append([nums[i], nums[left], nums[right]])

                # Skip duplicates for the second element
                while left < right and nums[left] == nums[left + 1]:
                    left += 1
                # Skip duplicates for the third element
                while left < right and nums[right] == nums[right - 1]:
                    right -= 1

                left += 1
                right -= 1

            elif current_sum < 0:
                left += 1  # Need a larger sum
            else:
                right -= 1  # Need a smaller sum

    return result


 

Breaking Down the Solution

This solution combines multiple patterns from common two pointer problems on LeetCode:

  1. Sort the array first—this enables the two-pointer approach
  2. Fix one element with the outer loop, then solve the two-sum problem for the remaining array
  3. Skip duplicates at multiple levels to ensure unique triplets
  4. Adjust pointers based on the sum comparison
    For a deeper dive into handling edge cases in such problems, check out our guide on Binary Search Explained: Algorithm, Examples, & Edge Cases, which covers similar considerations.

Problem 5: Container With Most Water (LeetCode 11)

This problem is unique among common two pointer problems on LeetCode because it doesn’t require the array to be sorted, yet the two-pointer approach works perfectly.

Problem Analysis

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49

We need to find two lines that together with the x-axis form a container that holds the most water. The area is determined by the shorter line times the distance between lines.

The Two-Pointer Solution

 

Python

def maxArea(self, height):
    left, right = 0, len(height) - 1
    max_water = 0

    while left < right:
        # Calculate current area
        width = right - left
        current_height = min(height[left], height[right])
        current_area = width * current_height

        # Update maximum
        max_water = max(max_water, current_area)

        # Move the pointer pointing to the shorter line
        if height[left] < height[right]:
            left += 1
        else:
            right -= 1

    return max_water


 

The Intuition

The logic behind moving pointers is crucial: we always move the pointer pointing to the shorter line. Why? Because the area is limited by the shorter height. If we move the taller line, any new container will have the same or smaller width but cannot have a greater height (since we’re moving toward the shorter line). Therefore, the only chance to increase area is to move the shorter line, hoping to find a taller one.

Problem 6: Trapping Rain Water (LeetCode 42)

This is one of the more challenging common two pointer problems on LeetCode. It builds on the container concept but requires a more sophisticated approach.

Problem Analysis

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

We need to calculate how much water can be trapped between the bars after raining.

The Two-Pointer Solution

 

Python

def trap(self, height):
    if not height:
        return 0

    left, right = 0, len(height) - 1
    left_max, right_max = height[left], height[right]
    water_trapped = 0

    while left < right:
        if left_max < right_max:
            left += 1
            left_max = max(left_max, height[left])
            water_trapped += left_max - height[left]
        else:
            right -= 1
            right_max = max(right_max, height[right])
            water_trapped += right_max - height[right]

    return water_trapped


 

How It Works

This solution uses the concept of prefix maximums and suffix maximums but applies it in a single pass:

  • We maintain the maximum height seen from the left (left_max) and from the right (right_max)
  • At each step, we work from the side with the smaller maximum
  • Water trapped at a position is the difference between the current maximum and the height at that position

Problem-Solving Patterns in Two Pointer Problems

As you work through more common two pointer problems on LeetCode, you’ll start recognizing recurring patterns:

Pattern 1: Opposite Direction (Converging)

Used in problems like Two Sum II and Valid Palindrome where pointers start at ends and move toward each other.

Pattern 2: Same Direction (Sliding Window)

Used in problems like Remove Duplicates where both pointers move forward but at different speeds.

Pattern 3: Multiple Pointers

Used in 3Sum where we fix one pointer and use two others for the remaining subarray.

For a structured approach to learning these patterns, our Complete Data Structures & Algorithms Series provides comprehensive coverage of all major algorithm patterns.

Common Pitfalls and How to Avoid Them

When solving common two pointer problems on LeetCode, watch out for these frequent mistakes:

1. Forgetting to Handle Duplicates

In problems like 3Sum, failing to skip duplicates can lead to duplicate triplets in the result.

 

Python

# Correct way to skip duplicates
if i > 0 and nums[i] == nums[i-1]:
    continue


 

2. Off-by-One Errors

Always be careful with array indices, especially when dealing with 1-indexed vs 0-indexed returns.

3. Infinite Loops

Ensure pointers always move in each iteration. A common bug is forgetting to increment/decrement pointers when conditions are met.

4. Not Considering Edge Cases

Always check for empty arrays, single elements, or arrays with all identical elements.

For more debugging strategies, check out 5 Debugging Tricks Professors Won’t Teach You.

Advanced Two Pointer Problems

Once you’ve mastered the basics, challenge yourself with these more complex problems:

  • 4Sum (LeetCode 18): Extends the 3Sum pattern
  • Sort Colors (LeetCode 75): Uses three pointers
  • Minimum Window Substring (LeetCode 76): Combines two pointers with hashing
  • Subarray Product Less Than K (LeetCode 713): Uses sliding window pattern
    These problems appear frequently in coding interviews and will test your understanding of the two-pointer technique in more complex scenarios. For tackling such challenges, our guide on How to Approach Hard LeetCode Problems | A Strategic Framework provides valuable strategies.

Integrating Two Pointers with Other Data Structures

While we’ve focused on arrays, the two-pointer technique can be combined with other data structures:

Two Pointers on Linked Lists

Problems like detecting cycles (Floyd’s algorithm) or finding the middle node use two pointers effectively. Learn more in our Stack and Queue Implementation Guide | LIFO & FIFO Explained.

Some problems benefit from combining two pointers with binary search for even better optimization.

Two Pointers on Strings

String problems like “Longest Palindromic Substring” often use two pointers expanding from the center.

Tips for Coding Interviews

When you encounter common two pointer problems on LeetCode in actual interviews:

  1. Clarify assumptions: Ask if the array is sorted, if modifications are allowed, and about duplicate handling.
  2. Start with brute force: Even if you know the optimal solution, briefly discuss the naive approach and its complexity.
  3. Explain the intuition: Don’t just code—explain why the two-pointer approach works for this specific problem.
  4. Walk through an example: Trace through a small test case to verify your logic.
  5. Consider edge cases: Mention how your code handles empty arrays, single elements, or all identical elements.
    For comprehensive interview preparation, our Mastering Data Structures for Coding Interviews | Step-by-Step Roadmap is an invaluable resource.

Practice Schedule for Mastery

To truly master common two pointer problems on LeetCode, follow this structured practice schedule:

Week 1: Fundamentals

  • Two Sum II (167)
  • Valid Palindrome (125)
  • Remove Duplicates (26)

Week 2: Intermediate

  • 3Sum (15)
  • Container With Most Water (11)
  • 3Sum Closest (16)

Week 3: Advanced

  • Trapping Rain Water (42)
  • 4Sum (18)
  • Sort Colors (75)

Week 4: Mixed Practice

Combine two-pointer problems with other patterns to build flexibility and recognition.

Conclusion

Mastering common two pointer problems on LeetCode is a journey that pays significant dividends in coding interviews. The problems we’ve covered represent the core patterns you’ll encounter repeatedly:

  • Opposite direction pointers for sorted arrays and palindromes
  • Same direction pointers for in-place modifications
  • Fixed + moving pointers for k-sum problems
  • Dynamic adjustment based on constraints like water trapping
    The key to success is not memorizing solutions but understanding the underlying patterns. When you see a problem involving pairs, triplets, or in-place modifications in a linear data structure, ask yourself: “Can two pointers solve this more efficiently?”

Remember that the two-pointer technique is just one tool in your algorithmic toolkit. As you progress in your coding journey, you’ll combine it with other techniques like sliding windows, binary search, and dynamic programming to solve increasingly complex problems.

We encourage you to practice these problems regularly, trace through the solutions on paper, and gradually reduce your reliance on seeing the answer. Soon, recognizing when and how to apply the two-pointer technique will become second nature.

For continued learning, explore our Building Problem-Solving Skills as a Developer | Engineering Mindset guide, which helps develop the right mindset for tackling any coding challenge.

Frequently Asked Questions

Q: Do I always need a sorted array for the two-pointer technique?

A: Not always. While many two-pointer problems require sorted arrays (like Two Sum II), others like “Container With Most Water” and “Valid Palindrome” work on unsorted data. The key is understanding why sorting helps—it allows us to make decisions about moving pointers based on comparisons.

Q: How do I know which pointer to move in two-pointer problems?

A: The decision depends on the problem’s goal. In sum-based problems, move the left pointer if you need a larger sum and the right pointer if you need a smaller sum. In water container problems, move the pointer pointing to the shorter line. Always think about what moving each pointer accomplishes.

Q: Can two pointers solve all array problems?

A: No, two pointers excel at problems involving pairs, triplets, or palindromes in linear data structures. However, problems requiring different patterns—like those needing frequency counts or complex state tracking—might be better solved with hash maps, sliding windows, or other techniques.

Q: How is the two-pointer technique different from the sliding window approach?

A: While both use two pointers, sliding window typically maintains a contiguous window that expands and contracts, often tracking additional state like sums or counts. Classic two-pointer problems usually compare elements at pointer positions without maintaining window state.

Q: What’s the best way to practice two-pointer problems?

A: Start with the fundamentals (Two Sum II, Valid Palindrome), then progress to more complex problems (3Sum, Trapping Rain Water). For each problem, try to solve it without looking at the solution, then compare your approach with optimal solutions. Regular, spaced repetition is key to mastery.

For personalized help with coding problems, check out Where to Get Reliable Coding Assignment Help and Python Assignment Help: A Complete Student Guide.


Ready to master more algorithms? Explore our Complete Data Structures & Algorithms Series for in-depth guides on every major topic you’ll encounter in coding interviews.

Next Steps

Mastering common two pointer problems on LeetCode is a significant milestone in any coder's journey, significantly enhancing problem-solving skills and coding interview prep. By understanding the two-pointer technique and practicing its application through the problems outlined in this guide, you've taken a substantial step towards improving your algorithmic prowess.

However, the journey to coding mastery is ongoing. To further refine your skills and tackle more complex challenges, consider personalized tutoring with experienced professionals who can provide tailored guidance and feedback. Through platforms like CodeAssistPro's tutoring services, you can access expert mentors who will help you navigate intricate coding concepts, review your code, and offer invaluable insights to accelerate your learning.

If you're working on specific assignments, projects, or need expert opinions on your code, leveraging services like CodeAssistPro's expert code review can be instrumental. Their team of seasoned experts can review your code, provide detailed feedback, and help you optimize your solutions, ensuring you're on the right track to achieving coding excellence.

To continue enhancing your coding abilities, especially with the two-pointer technique, we recommend:

  • Practicing a wide range of problems on LeetCode and other coding platforms to deepen your understanding and versatility with the two-pointer technique.
  • Exploring more advanced algorithmic patterns and techniques, such as sliding window, binary search, and divide and conquer, to expand your problem-solving toolkit.
  • Engaging with the coding community, participating in coding challenges, and contributing to open-source projects to stay updated with the latest trends and best practices in coding.

By combining diligent practice, expert guidance, and a commitment to continuous learning, you'll not only master the two-pointer technique but also significantly improve your overall coding skills, setting yourself up for success in both coding interviews and your professional coding endeavors.


Related Posts

Binary Search Explained: Algorithm, Examples, & Edge Cases

Master the binary search algorithm with clear, step-by-step examples. Learn how to implement efficient searches in sorted arrays, avoid common …

Mar 11, 2026
How to Approach Hard LeetCode Problems | A Strategic Framework

Master the mental framework and strategies to confidently break down and solve even the most challenging LeetCode problems.

Mar 06, 2026
Two Pointer Technique | Master Array Problems in 8 Steps

Master the two-pointer technique to solve complex array and string problems efficiently. This guide breaks down patterns, provides step-by-step examples, …

Mar 11, 2026

Need Coding Help?

Get expert assistance with your programming assignments and projects.