Minimum distance to the target element

November 16, 2022

array-and-hashmap

Problem URL: Minimum distance to the target element

We will iterate over all the elements and find the minimum distance.

class Solution:
    def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
        return min(abs(i - start) for i, num in enumerate(nums) if num == target)

Time complexity: O(n)
Space complexity: O(1)