array and hashmap November 16, 2022

Minimum distance to the target element

Time O(n) Space O(1) Open original problem

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)