Show problems as
Classic problem #1848EasyArray

Minimum Distance to the Target Element

Real-world version: Nearest Matching Bin
Tracked in this browser only
Read Minimum Distance to the Target Element on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A single aisle of a stockroom holds bins side by side. labels[i] is the part number sitting in bin i, and a part number may appear in several bins. A picker is standing in front of bin start and needs the part numbered target.

Walking from bin i to bin j costs |i - j| paces. Return the smallest number of paces the picker must walk to stand in front of a bin holding target. The aisle is guaranteed to hold target in at least one bin.

Examples

Example 1

Input
labels = [7, 2, 9, 2, 7], target = 2, start = 2
Output
1

Bins 1 and 3 both hold part 2 and the picker stands at bin 2, so either one is a single pace away.

Example 2

Input
labels = [9, 1, 1, 1, 42], target = 42, start = 0
Output
4

Part 42 sits only in bin 4 and the picker stands at bin 0, so the walk is four paces.

Example 3

Input
labels = [2, 5, 2, 5, 2], target = 5, start = 4
Output
1

Part 5 sits in bins 1 and 3 while the picker stands at bin 4, so bin 3 is one pace away.

Constraints

  • 1 <= labels.length <= 1000
  • 1 <= labels[i] <= 10^4
  • 0 <= start < labels.length
  • target appears in labels at least once.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def nearest_matching_bin(labels: list[int], target: int, start: int) -> int:
Java
public int nearestMatchingBin(int[] labels, int target, int start)