awelgorithms

One pointer per sorted sequence

Updated

i walks a. j walks b. Both start at 0. Each sequence has its own index. They do not share a cursor. a and b must already be sorted.

What to focus on

a[i] is the unused head of a. b[j] is the unused head of b. i < a.length and j < b.length until a sequence is exhausted.

Worked examples

start

a = [1, 4, 9], b = [4, 7, 9], i=0 j=0
  1. head a is 1
  2. head b is 4

Result: two heads, two indices

after one step

a = [1, 4, 9], b = [4, 7, 9], i=1 j=0
  1. head a is 4
  2. head b is 4

Result: i moved, j stayed

unequal lengths

a = [1, 4, 9], b = [7], i=0 j=0
  1. head a is 1
  2. head b is 7

Result: i and j still independent

Try it

Write initPointers(a, b). a is a sorted array of integers. b is a second sorted array. i is the index on a. j is the index on b. Return (i, j) = (0, 0). For [1, 4, 9] vs [4, 7, 9] and vs [7].

a and b are nonempty and sorted non-decreasing.