awelgorithms

Deduplicate pairs at both pointers

Updated

After recording a pair on a sorted array, skip equal neighbors on L and on R so (1, 9) is emitted once even if 1 or 9 repeats.

What to focus on

Skip only after a hit. While L < R and a[L] equals the used left, L += 1. Same on R downward. Do not skip the first copy before you use it.

Worked examples

extra 4

a = [1, 4, 4, 9], target=5
  1. L=0, R=3: 1+9=10 > 5, R=2
  2. 1+4=5 hit
  3. skip extra 4s on R

Result: record (1, 4) once · L=1, R=0

extra 1

a = [1, 1, 4, 9], target=10
  1. L=0, R=3: 1+9=10 hit
  2. L += 1 while a[L]==1 → L=2

Result: record (1, 9) once · L=2, R=2

no dups

a = [1, 4, 9], target=10
  1. L=0, R=2 hit
  2. L=1, R=1
  3. no equal neighbor to skip

Result: record (1, 9) once

Try it

Write uniquePairs(a, target). a is a sorted array of integers. target is the pair sum. L is the left index. R is the right index. Duplicates if present are adjacent. Record each value-pair once. Skip equal neighbors after a hit. Return the unique pairs. On [1, 4, 4, 9] target 5, [1, 1, 4, 9] target 10, and [1, 4, 9] target 10, each value-pair appears once.

a is sorted non-decreasing, length ≥ 2. A target pair exists. Duplicates if present are adjacent.