Ctrl K

Nearest Match from the Start

Easy
You are given an integer array values, a number target and a zero-based index start. The target is guaranteed to appear in the array at least once. Among all positions i with values[i] == target, pick the one closest to start and return the distance to it, that is |i - start|.
Example 1
values=[4, 7, 2, 7, 9, 4], target=4, start=3 → 2

The value 4 sits at positions 0 and 5. From position 3 they are 3 and 2 steps away, so position 5 is closer.

Example 2
values=[8, 3, 8], target=8, start=0 → 0

The target is right at the starting position, so the distance is 0.

Constraints
  • 1 ≤ values.length ≤ 1000
  • -10⁴ ≤ values[i] ≤ 10⁴
  • 0 ≤ start < values.length
  • target occurs in values
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPair With a Target Sum EasySqueeze Repeats Out of a Sorted Array EasyDrop the Unwanted Value EasySlot on a Sorted Shelf EasyAdd One to a Digit Array Easy
loading Python…
Input
values=[4, 7, 2, 7, 9, 4], target=4, start=3
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 119 tests on the server, hidden ones included.