Minimum Distance to the Target Element — LeetCode 1848 Python Solution

EasyArray
Problem
#1848
Reading time
2 min

The problem

Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute value of x.

Example

Input
nums = [1,2,3,4,5], target = 5, start = 3
Output
1
Explanation
nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.

Python solution

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

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array nums
SpaceO(1) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1848. Minimum Distance to the Target Element?
LeetCode 1848. Minimum Distance to the Target Element is rated Easy on LeetCode.
What is the time complexity of LeetCode 1848. Minimum Distance to the Target Element?
The Python solution on this page runs in O(n), where n is the length of the array nums.
What is the space complexity of LeetCode 1848. Minimum Distance to the Target Element?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1848. Minimum Distance to the Target Element cover?
LeetCode 1848. Minimum Distance to the Target Element is tagged Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview