awelgorithms

Accept a pair and record it

Updated

Accepting means the pair matches the rule, so you store (L, R) or (a[L], a[R]). Recording writes the answer, not the array. Then you still move so you do not record the same indices again.

What to focus on

After accept, the answer contains that pair once. A hit on opposite ends usually then does L += 1 and R -= 1.

Worked examples

target 10

a = [1, 4, 9], target=10, L=0, R=2
  1. L=0, R=2
  2. 1+9=10
  3. record then L+=1, R-=1

Result: recorded (1, 9) · L=1, R=1

values

a = [4, 1, 9], L=0, R=1
  1. L=0, R=1
  2. accept (4, 1)
  3. record indices (0, 1)

Result: recorded (4, 1) at (0, 1)

one

a = [7], L=0, R=0
  1. L=0, R=0
  2. self-pair is not two indices

Result: no pair recorded

Try it

Write acceptPair(a, L, R, target). a is an array of integers. L is the left index. R is the right index. target is the pair sum when used. Record the pair, then move so you do not record the same indices again. Print the record. On sorted [1, 4, 9] target 10 at (0, 2) and target 13 at (1, 2), and on [4, 1, 9] at (0, 1).

a has length ≥ 2. L and R are distinct in-range indices. The current pair matches the accept rule.