#1848
Minimum Distance to the Target Element
EasyArrayArrayLinear Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of checking every index, we can loop through the array once and keep track of the minimum distance as we find the target. This reduces unnecessary checks and is more efficient.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a variable to store the minimum distance as infinity.
- 2Step 2: Loop through each index in the array.
- 3Step 3: If the current element equals the target, calculate the absolute distance from the start index and update the minimum distance if it's smaller.
- 4Step 4: Return the minimum distance.
solution.py6 lines
1def getMinDistance(nums, target, start):
2 min_distance = float('inf')
3 for i in range(len(nums)):
4 if nums[i] == target:
5 min_distance = min(min_distance, abs(i - start))
6 return min_distanceℹ
Complexity note: The time complexity is O(n) because we check each element once. The space complexity is O(1) since we only use a few variables for tracking distances.
- 1The problem guarantees that the target exists, so we don't need to handle cases where it doesn't.
- 2The distance is always calculated as an absolute value, which simplifies our checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.