awelgorithms

Reject a pair and move on

Updated

Rejecting means the pair fails the rule. Do not record it. Move a pointer and read the next pair.

What to focus on

After reject, the answer is unchanged. Exactly the chosen end moves. You never record a rejected pair.

Worked examples

too large

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

Result: no record · L=0, R=1

too small

a = [1, 4, 9], target=13, L=0, R=2
  1. L=0, R=2
  2. 1+9=10 ≠ 13
  3. L += 1

Result: no record · L=1, R=2

one

a = [7], target=10
  1. no second index
  2. nothing to reject as a pair

Result: no pair · no record

Try it

Write rejectPair(a, L, R, target). a is a sorted array of integers. L is the left index. R is the right index. target is the pair sum that this pair is not. Do not record. Move one end. Print the new L, R. On [1, 4, 9] targets 8 and 13 from (0, 2), and target 5 from (1, 2).

a is sorted non-decreasing, length ≥ 2. The current pair is not the target.