Given an integer array nums
(0-indexed) and two integers target
and start
, find the minimum distance between start
and any index i
such that nums[i] == target
.
Example:
nums = [1, 2, 3, 4, 5]
target = 5
start = 3
# Output: 1
Initialize a variable to store the minimum distance found so far (min_distance
). Another variable (distance
) to calculate the absolute difference between start
and i
.
Iterate through the nums
array and check for elements equal to target
.
Update min_distance
each time a closer index i
to start
is found.
Return the minimum distance after the loop ends.
Let’s discuss the time complexity here. We need to iterate through the entire list once, making our solution run in O(n) time complexity, where n is the length of nums
.
def getMinDistance(nums, target, start):
"""
:type nums: List[int]
:type target: int
:type start: int
:rtype: int
"""
min_distance = float('inf')
for i in range(len(nums)):
if nums[i] == target:
distance = abs(i - start)
if distance < min_distance:
min_distance = distance
return min_distance
# Example usage:
nums = [1, 2, 3, 4, 5]
target = 5
start = 3
print(getMinDistance(nums, target, start)) # Output: 1
Initialization: min_distance
is set to a very high value initially (float('inf')
), this will help in finding the minimum value during comparisons.
Iterate through nums
: Check each element of nums
to see if it matches the target
.
Calculate the distance: Compute the absolute difference between the current index i
and start
.
Update min_distance
: Whenever a smaller distance is found, update min_distance
.
Return the smallest distance found.
This approach ensures we account for multiple occurrences of the target and handle possible edge cases while maintaining an O(n) time complexity.
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?