EasyNo. 1848
Minimum Distance to the Target Element — LeetCode 1848 Python Solution
- Topics
- Array
- Reading time
- 2 min
- Source
- leetcode.com
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
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
- Time
- O(n)where n is the length of the array nums
- Space · auxiliary
- O(1)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0057 | Insert Interval | Medium |
| 0228 | Summary Ranges | Easy |
| 0485 | Max Consecutive Ones | Easy |
| 0665 | Non-decreasing Array | Medium |
| 0674 | Longest Continuous Increasing Subsequence | Easy |
| 0699 | Falling Squares | Hard |
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.