awelgorithms

Close the gap from both ends

Updated

Closing the gap moves both ends inward in one step: L += 1 and R -= 1. The unprocessed slice loses one index on each side.

What to focus on

After a close step the new indices are the old L+1 and R-1. Everything outside the new [L, R] is finished. Odd n meets. Even n still has a two-cell slice, or crosses if you started on two cells.

Worked examples

three

a = [4, 1, 9]
  1. start L=0, R=2
  2. L+=1, R-=1

Result: L=1, R=1

four

a = [4, 1, 9, 1]
  1. start L=0, R=3
  2. L+=1, R-=1

Result: L=1, R=2

one

a = [7]
  1. start L=0, R=0
  2. already no gap; do not close

Result: L=0, R=0

Try it

Write closeGap(a). a is an array of integers. L is the left index, start 0. R is the right index, start n-1. Do L += 1 and R -= 1 once. Print the new L and R. Return nothing. On [4, 1, 9] print L=1, R=1. On [4, 1, 9, 1] print L=1, R=2. On [4, 1] print L=1, R=0.

a has length ≥ 2. Start with L = 0 and R = n-1.

LeetCode problems that use this skill