awelgorithms

Recognize an opposite-end search

Updated

Opposite-end: one index at 0, one at n-1, they close. Palindrome checks, container-with-water, sorted pair-sum. The discarded side is an end, not a prefix trail.

What to focus on

If both pointers start at 0 and chase, that is same-direction, not this. Draw L at the first cell and R at the last before coding.

Worked examples

pair sum

a = [1, 4, 9], t=13
  1. L=0 R=2
  2. move the end whose value makes the sum wrong

Result: opposite-end

palindrome

a = [1, 4, 1], L=0 R=2
  1. 1==1, L++ R--
  2. meet at 4

Result: opposite-end

not this

a = [0, 1, 0, 9], i=0 w=0 compact
  1. both start left
  2. only i and w grow

Result: same-direction trail

Try it

Write classify(a). a is an array of integers. Opposite-end uses L at 0 and R at n-1. Same-direction uses i and w both on the left. Print opposite-end or same-direction and name L,R or i,w. Return nothing. For a = [1, 4, 9] t=13, a = [1, 4, 1] palindrome, and a = [0, 1, 0, 9] compact.

a is nonempty, length ≥ 2. Pair-sum a is sorted.