Skip to main content

02 Two Pointers - 2 indexes

Requirement - Sorted array
Core Problem - Find 2 elements are in array which fulfil a certain criteria
Core Logic : For every loop cycle we check both left side and right side and also reduce search space for next cycle.

hashcomics
1 / 7
Panel 1
Panel 1
Panel 2
Panel 3
Panel 4
Panel 5
Panel 6
Panel 7

Steps:​

  1. Initialize two pointers, one at the start (left) and one at the end (right) of the array.
  2. Check the sum of the elements at the two pointers.
  3. If the sum equals the target, return the indices.
  4. If the sum is less than the target, move the left pointer to the right.
  5. If the sum is greater than the target, move the right pointer to the left.

Sample Problem:​

Find two numbers in a sorted array that add up to a target value.

  • Input: nums = [1, 2, 3, 4, 6], target = 6
  • Output: [1, 3]

LeetCode Problems:​

  1. Two Sum II - Input Array is Sorted (LeetCode #167)
  2. 3Sum (LeetCode #15)
  3. Container With Most Water (LeetCode #11)