Leetcode 1848. Minimum Distance to the Target Element
Leetcode problem 1848: “Minimum Distance to the Target Element”
Given an integer array nums
and two integers target
and start
, find the minimum distance between start
and any position i
such that nums[i] == target
.
The distance between two indices i
and j
is |i - j|
, where ||
represents the absolute value function.
Return the minimum distance. If there is no such i
, return -1.
nums
?
start
be out of the bounds of the array?
start
is guaranteed to be within the bounds of the array.To solve this problem, we need to iterate through the array and look for all occurrences of target
. For each occurrence, we’ll calculate the distance to start
and keep track of the minimum distance found.
minDistance
to Integer.MAX_VALUE
.nums
:
nums[i]
equals target
, calculate the distance |i - start|
.minDistance
if the new calculated distance is smaller.minDistance
remains Integer.MAX_VALUE
, return -1
(indicating no target was found).minDistance
.public class Solution {
public int getMinDistance(int[] nums, int target, int start) {
int minDistance = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
int distance = Math.abs(i - start);
minDistance = Math.min(minDistance, distance);
}
}
return minDistance == Integer.MAX_VALUE ? -1 : minDistance;
}
}
n
is the length of the array nums
, because we are making a single pass over the array.minDistance
and distance
.This solution is efficient and conforms to Leetcode’s typical constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?