Converging pointers

2 snippets in Interview Prep

DSAInterview Prep

Two Pointers Technique

DSA · Arrays & Strings
syntax
Use two indices (left and right) moving toward each other or in the same direction.
Works on sorted arrays or when searching for pairs.
example
// JavaScript — Find pair that sums to target in sorted array
function twoSumSorted(arr, target) {
  let left = 0, right = arr.length - 1;
  while (left < right) {
    const sum = arr[left] + arr[right];
    if (sum === target) return [left, right];
    else if (sum < target) left++;
    else right--;
  }
  return [-1, -1];
}

# Python
def two_sum_sorted(arr, target):
    left, right = 0, len(arr) - 1
    while left < right:
        total = arr[left] + arr[right]
        if total == target:
            return [left, right]
        elif total < target:
            left += 1
        else:
            right -= 1
    return [-1, -1]
output
twoSumSorted([1,3,5,7,9], 8) → [1, 3]

Note Time O(n), Space O(1). Requires sorted input for the converging pattern. Edge cases: empty array, single element, no valid pair. Tell the interviewer you chose two pointers over hash map to achieve O(1) space.

Pattern: Two Pointers

DSA · Common Patterns Summary
syntax
When to use:
- Sorted array pair problems
- Removing duplicates in place
- Container with most water
- Palindrome checking

Variants:
- Opposite ends (converging)
- Same direction (fast/slow or lagging)
example
// JavaScript — Remove duplicates from sorted array
function removeDuplicates(arr) {
  if (arr.length === 0) return 0;
  let writeIdx = 1;
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] !== arr[i - 1]) {
      arr[writeIdx] = arr[i];
      writeIdx++;
    }
  }
  return writeIdx;
}

# Python
def remove_duplicates(arr):
    if not arr:
        return 0
    write_idx = 1
    for i in range(1, len(arr)):
        if arr[i] != arr[i - 1]:
            arr[write_idx] = arr[i]
            write_idx += 1
    return write_idx
output
remove_duplicates([1,1,2,2,3]) → 3, arr becomes [1,2,3,...]

Note O(n) time, O(1) space. The 'read pointer / write pointer' variant is essential for in-place array problems. Always ask: is the input sorted? If yes, two pointers likely applies. If unsorted, consider hash set instead.