Overview
We are looking for "closest" to either end so that means we only care about the "first match" (from left/start) and "last index" (from last/end).
Sample #1
Given: [5, 5, 5, 5, 5, 5, 3]
Say we look for a match of "5"
- first left match is on left end (zero positions from left end) = 0
- first right match is one from right end (one position from right end) = 1
- 0 < 1, so "left" wins. In other words, the first left match is closer to the left end (0) than the first right match is to the right end (1).
- Now we return result as actual array index, because it's left end, it would simply be 0.
Sample #2
Given: [8, 9, 5, 5, 5, 5, 5, 5, 0]
Say we look for a match of "5"
- first left match is two from left end (two positions from left end) = 2
- first right match is one from right end (one position from right end) = 1
- 1 < 2, so "right" wins. In other words, the first right match is closer to the right end (1) than the left match is to the left end (2).
- Now we return result as actual array index, because it's right end, we have to convert to actual array index which is always from left end and zero-based, so in this case we return 7