Minimum Distance to the Target Element
Real-world version: Nearest Matching BinThe 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.
def nearest_matching_bin(labels: list[int], target: int, start: int) -> int:public int nearestMatchingBin(int[] labels, int target, int start)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 12 test cases: 12 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's