awelgorithms

Place opposite-end pointers

Updated

Opposite-end placement puts L at index 0 and R at index n-1 so the two indices face each other across the whole array. You name them from length. You do not scan to find the ends.

What to focus on

After placement, L = 0 and R = n-1, and L ≤ R. n = 1 lands both on the only cell.

Worked examples

three

a = [4, 1, 9]
  1. n = 3
  2. L ← 0, R ← 2
  3. a[0]=4 faces a[2]=9

Result: L=0, R=2

four

a = [4, 1, 9, 1]
  1. n = 4
  2. L ← 0, R ← 3

Result: L=0, R=3

empty

a = []
  1. n = 0
  2. there is no index 0 or n-1

Result: no L, R

Try it

Write placeEnds(a). a is an array of integers. L is the left index. R is the right index. Set L = 0 and R = n-1 when n ≥ 1. Print L and R after placement. On empty, print that there is no L or R. On [4, 1, 9] print L=0, R=2. On [4, 1, 9, 1] print L=0, R=3. On [] print no L, R.

a may be empty. When nonempty, length ≥ 1.

LeetCode problems that use this skill