DEV Community

M.T.Ramkrushna
M.T.Ramkrushna

Posted on

DSA: Topic 3: Two Pointers

Interview frequency: ⭐⭐⭐⭐⭐ (Top 5 pattern)

Many candidates fail interviews not because they don't know algorithms, but because they don't recognise when to use Two Pointers.


What is the Two Pointers technique?

Instead of using one index:

i = 0
Enter fullscreen mode Exit fullscreen mode

you use two indices.

left = 0
right = len(arr) - 1
Enter fullscreen mode Exit fullscreen mode

These pointers move based on the problem.

Example:

Index : 0  1  2  3  4

Array : 2  4  7  9  15
         ↑         ↑
       left      right
Enter fullscreen mode Exit fullscreen mode

The pointers may:

  • Move towards each other
  • Move in the same direction
  • Move at different speeds

When should you think of Two Pointers?

This is the most important part.

Whenever you see:

  • Sorted array
  • Pair problems
  • Remove duplicates
  • Move elements
  • Reverse array/string
  • Palindrome
  • Merge sorted arrays

Your brain should immediately ask:

"Can I solve this using two pointers?"


Pattern 1: Opposite Direction

Pointers start from both ends.

L ------------->

<------------- R
Enter fullscreen mode Exit fullscreen mode

Used for:

  • Pair Sum
  • Reverse Array
  • Palindrome
  • Container With Most Water

Example 1: Reverse an Array

Input

nums = [1,2,3,4,5]
Enter fullscreen mode Exit fullscreen mode

Instead of creating another array, swap from both ends.

left = 0
right = len(nums)-1

while left < right:
    nums[left], nums[right] = nums[right], nums[left]

    left += 1
    right -= 1
Enter fullscreen mode Exit fullscreen mode

Output

[5,4,3,2,1]
Enter fullscreen mode Exit fullscreen mode

Complexity

Time : O(n)

Space: O(1)
Enter fullscreen mode Exit fullscreen mode

Interviewers love in-place solutions.


Example 2: Valid Palindrome

madam
Enter fullscreen mode Exit fullscreen mode
m == m

a == a

d
Enter fullscreen mode Exit fullscreen mode

Algorithm

left = 0

right = len(s)-1

while left < right:

    if s[left] != s[right]:
        return False

    left += 1

    right -= 1

return True
Enter fullscreen mode Exit fullscreen mode

Time

O(n)
Enter fullscreen mode Exit fullscreen mode

Very common interview problem.


Example 3: Two Sum II (Sorted Array)

Input

[2,4,7,11,15]

target = 18
Enter fullscreen mode Exit fullscreen mode

Instead of checking every pair:

2 + 15 = 17

Need larger

Move left
Enter fullscreen mode Exit fullscreen mode
4 + 15 = 19

Too large

Move right
Enter fullscreen mode Exit fullscreen mode
4 + 11 = 15

Need larger

Move left
Enter fullscreen mode Exit fullscreen mode
7 + 11 = 18

Found
Enter fullscreen mode Exit fullscreen mode

Code

left = 0
right = len(nums)-1

while left < right:

    total = nums[left] + nums[right]

    if total == target:
        return [left,right]

    elif total < target:
        left += 1

    else:
        right -= 1
Enter fullscreen mode Exit fullscreen mode

Notice how the sorted property lets us decide which pointer to move.


Pattern 2: Same Direction

Used for:

  • Remove duplicates
  • Move zeroes
  • Partition arrays

Example:

[0,1,0,3,12]
Enter fullscreen mode Exit fullscreen mode

Expected

[1,3,12,0,0]
Enter fullscreen mode Exit fullscreen mode

Use

slow

fast
Enter fullscreen mode Exit fullscreen mode

Fast explores.

Slow remembers where the next valid element should go.


Move Zeroes

slow = 0

for fast in range(len(nums)):

    if nums[fast] != 0:

        nums[slow], nums[fast] = nums[fast], nums[slow]

        slow += 1
Enter fullscreen mode Exit fullscreen mode

Output

[1,3,12,0,0]
Enter fullscreen mode Exit fullscreen mode

Interview frequency:

⭐⭐⭐⭐⭐


Pattern 3: Fast and Slow Pointer

Mostly used in Linked Lists.

slow

fast
Enter fullscreen mode Exit fullscreen mode
slow -> 1 step

fast -> 2 steps
Enter fullscreen mode Exit fullscreen mode

Applications

  • Detect cycle
  • Find middle node
  • Happy Number

We'll revisit this when we study linked lists.


How to Identify Two Pointer Problems

Ask yourself:

Is the array sorted?

Example

Pair Sum
Enter fullscreen mode Exit fullscreen mode

Use opposite pointers.


Do I need to compare two ends?

Palindrome

Reverse String
Enter fullscreen mode Exit fullscreen mode

Use opposite pointers.


Am I moving/removing elements?

Move Zeroes

Remove Duplicates
Enter fullscreen mode Exit fullscreen mode

Use slow and fast pointers.


Am I merging two sorted arrays?

Use one pointer for each array.


Common Interview Mistakes

Mistake 1

Using nested loops.

for i:

    for j:
Enter fullscreen mode Exit fullscreen mode

Many pair problems can be solved with two pointers in O(n) instead of O(n²).


Mistake 2

Using Two Pointers on an unsorted array when the problem depends on order.

For example:

Two Sum
Enter fullscreen mode Exit fullscreen mode

If the array isn't sorted and you can't sort it (because you need original indices), use a Hash Map instead.


Mistake 3

Moving the wrong pointer.

Remember:

If the array is sorted:

Sum too small

Move left
Enter fullscreen mode Exit fullscreen mode
Sum too big

Move right
Enter fullscreen mode Exit fullscreen mode

Real Interview Questions

Master these:

  1. Valid Palindrome ⭐⭐⭐⭐⭐
  2. Reverse String ⭐⭐⭐⭐⭐
  3. Two Sum II ⭐⭐⭐⭐
  4. Move Zeroes ⭐⭐⭐⭐⭐
  5. Remove Duplicates from Sorted Array ⭐⭐⭐⭐⭐
  6. Squares of a Sorted Array ⭐⭐⭐⭐
  7. Container With Most Water ⭐⭐⭐⭐
  8. 3Sum ⭐⭐⭐⭐⭐ (advanced extension)

Interview Thinking Process

Suppose you're asked:

"Given a sorted array, find two numbers whose sum is target."

A strong interview approach is:

  1. Notice the array is sorted.
  2. Recognise that brute force (O(n²)) is unnecessary.
  3. Suggest using two pointers (left, right).
  4. Explain why moving left increases the sum and moving right decreases it.
  5. Code the O(n) solution.

This demonstrates both algorithmic knowledge and problem-solving, which is exactly what interviewers evaluate.

Next Topic

The next topic is Sliding Window, which is often confused with Two Pointers but solves a different class of problems such as:

  • Longest substring without repeating characters
  • Maximum sum subarray of size k
  • Minimum window substring
  • Longest repeating character replacement

Sliding Window is another ⭐⭐⭐⭐⭐ interview pattern and builds directly on the pointer concepts you've just learned.

Top comments (0)