Browse Curriculum

Two Pointers

Visualize the Two Pointers technique for finding a pair with a specific sum in a sorted array.

Ready to find pair.
2
0
3
1
5
2
8
3
11
4
14
5
18
6
23
7

Intuition

Instead of using nested loops to check every pair (O(n²)), we can use two pointers starting at the ends of a sorted array to find a pair with a target sum in O(n) time.

Concept

  • Sorted Array: Essential for this technique.
  • Left Pointer (L): Starts at 0.
  • Right Pointer (R): Starts at n-1.
  • Logic: If sum < target, we need a larger sum, so move L right. If sum > target, we need a smaller sum, so move R left.

How it Works

Algorithm:

  1. Initialize L = 0, R = n - 1.
  2. While L < R:
  3. Calculate sum = arr[L] + arr[R].
  4. If sum == target, return pair.
  5. If sum < target, increment L.
  6. If sum > target, decrement R.

Step-by-Step Breakdown

Watch the visualization:

  • See how the pointers move towards each other.
  • Notice that we never check the same pair twice or backtrack.

When to Use

  • Finding pairs in a sorted array.
  • Reversing an array (swapping elements at L and R).
  • Partitioning (like in QuickSort).

When NOT to Use

  • Unsorted arrays (unless you sort them first).
  • When you need to find indices in the original unsorted array (indices change after sorting).

How to Identify

"Find a pair...", "Sorted array", "In-place reversal".

Frequently Asked Questions

What is Two Pointers?

Visualize the Two Pointers technique for finding a pair with a specific sum in a sorted array.


What is the time complexity of Two Pointers?

The time complexity is: Best case varies, Average case O(N), Worst case varies. Space complexity is varies.