1848. Minimum Distance to the Target Element
Problem Description
You are given an integer array nums
(0-indexed), a target
value, and a start
index. Your task is to find an index i
in the array where nums[i]
equals target
, and the distance between i
and start
is as small as possible.
The distance is calculated as the absolute difference: abs(i - start)
, where abs(x)
represents the absolute value of x
.
Return the minimum distance abs(i - start)
.
The problem guarantees that the target
value exists at least once in the array nums
.
For example, if nums = [1, 2, 3, 4, 5]
, target = 3
, and start = 4
, the target value 3 appears at index 2. The distance would be abs(2 - 4) = 2
.
The solution approach iterates through the array once, identifies all indices where the value equals target
, calculates the distance from each of these indices to start
, and returns the minimum distance found.
Intuition
Since we need to find the minimum distance between the start
index and any index containing the target
value, the straightforward approach is to check all possible positions where target
appears in the array.
The key insight is that we don't need any complex algorithm or data structure - we simply need to examine every occurrence of target
and keep track of which one is closest to start
.
Think of it like finding the nearest gas station from your current location. You would check the distance to each gas station and pick the closest one. Similarly, we check the distance from start
to each index where target
appears.
The distance calculation abs(i - start)
handles both cases automatically:
- When the target is to the left of start (i < start), the distance is
start - i
- When the target is to the right of start (i > start), the distance is
i - start
By using the absolute value function, we don't need to worry about the direction - we just care about the magnitude of the distance.
Since we're guaranteed that target
exists in the array, we can confidently iterate through all elements, filter for those equal to target
, calculate their distances from start
, and return the minimum value found. This gives us an optimal solution in a single pass through the array with O(n) time complexity.
Solution Approach
The solution uses a single pass approach with Python's built-in functions to achieve a concise implementation.
The implementation breaks down into these steps:
-
Enumerate the array: Using
enumerate(nums)
, we get both the indexi
and the valuex
for each element in the array. -
Filter for target values: The condition
if x == target
filters the enumeration to only include indices where the value equals our target. -
Calculate distances: For each matching index
i
, we computeabs(i - start)
to get the distance from the start position. -
Find minimum: The
min()
function takes all these calculated distances and returns the smallest one.
The entire solution is implemented as a generator expression inside the min()
function:
min(abs(i - start) for i, x in enumerate(nums) if x == target)
This approach leverages Python's generator expression, which is memory-efficient as it doesn't create an intermediate list of all distances. Instead, it calculates distances on-the-fly and passes them to the min()
function.
Time Complexity: O(n) where n is the length of the array, as we traverse the entire array once.
Space Complexity: O(1) as we only use a constant amount of extra space - the generator doesn't store all distances simultaneously, it produces them one at a time for the min()
function to process.
The elegance of this solution lies in its simplicity - rather than using explicit loops and variables to track the minimum distance, it combines Python's functional programming features to solve the problem in a single, readable line of code.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through a concrete example to understand how the solution works.
Example: nums = [1, 2, 3, 4, 3]
, target = 3
, start = 0
Step 1: Enumerate the array We go through each element with its index:
- Index 0: value = 1
- Index 1: value = 2
- Index 2: value = 3 ✓ (matches target)
- Index 3: value = 4
- Index 4: value = 3 ✓ (matches target)
Step 2: Filter for target values We identify that the target value 3 appears at indices 2 and 4.
Step 3: Calculate distances from start
For each matching index, calculate the distance from start = 0
:
- Index 2:
abs(2 - 0) = 2
- Index 4:
abs(4 - 0) = 4
Step 4: Find the minimum distance Among the distances [2, 4], the minimum is 2.
Result: The minimum distance is 2.
Let's trace through one more example where the target appears on both sides of start:
Example: nums = [5, 3, 6, 3, 3]
, target = 3
, start = 2
- Target 3 appears at indices: 1, 3, and 4
- Distances from start (index 2):
- Index 1:
abs(1 - 2) = 1
(target is to the left) - Index 3:
abs(3 - 2) = 1
(target is to the right) - Index 4:
abs(4 - 2) = 2
(target is further right)
- Index 1:
- Minimum distance: 1
Notice how there's a tie (both indices 1 and 3 have distance 1). The solution correctly returns 1 as the minimum distance, regardless of which specific index achieves it.
Solution Implementation
1class Solution:
2 def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
3 """
4 Find the minimum distance between the start index and any index where target appears.
5
6 Args:
7 nums: List of integers to search through
8 target: The target value to find in the list
9 start: The starting index to measure distance from
10
11 Returns:
12 The minimum absolute distance from start to any occurrence of target
13 """
14 # Find all indices where the target value appears
15 # Calculate the absolute distance from each target index to the start index
16 # Return the minimum distance among all target occurrences
17 return min(abs(index - start) for index, value in enumerate(nums) if value == target)
18
1class Solution {
2 public int getMinDistance(int[] nums, int target, int start) {
3 // Get the length of the input array
4 int arrayLength = nums.length;
5
6 // Initialize minimum distance to the maximum possible value (array length)
7 int minDistance = arrayLength;
8
9 // Iterate through each element in the array
10 for (int currentIndex = 0; currentIndex < arrayLength; ++currentIndex) {
11 // Check if current element equals the target value
12 if (nums[currentIndex] == target) {
13 // Calculate distance between current index and start position
14 int currentDistance = Math.abs(currentIndex - start);
15
16 // Update minimum distance if current distance is smaller
17 minDistance = Math.min(minDistance, currentDistance);
18 }
19 }
20
21 // Return the minimum distance found
22 return minDistance;
23 }
24}
25
1class Solution {
2public:
3 int getMinDistance(vector<int>& nums, int target, int start) {
4 // Get the size of the input array
5 int arraySize = nums.size();
6
7 // Initialize minimum distance to maximum possible value (array size)
8 int minDistance = arraySize;
9
10 // Iterate through each element in the array
11 for (int i = 0; i < arraySize; ++i) {
12 // Check if current element equals the target value
13 if (nums[i] == target) {
14 // Update minimum distance if current distance is smaller
15 minDistance = min(minDistance, abs(i - start));
16 }
17 }
18
19 // Return the minimum distance found
20 return minDistance;
21 }
22};
23
1/**
2 * Finds the minimum distance between the start index and any occurrence of the target value in the array
3 * @param nums - The input array of numbers
4 * @param target - The target value to search for
5 * @param start - The starting index to calculate distance from
6 * @returns The minimum absolute distance between start and any index where target appears
7 */
8function getMinDistance(nums: number[], target: number, start: number): number {
9 // Initialize minimum distance to infinity
10 let minDistance: number = Infinity;
11
12 // Iterate through each element in the array
13 for (let i: number = 0; i < nums.length; i++) {
14 // Check if current element equals the target
15 if (nums[i] === target) {
16 // Update minimum distance if current distance is smaller
17 minDistance = Math.min(minDistance, Math.abs(i - start));
18 }
19 }
20
21 // Return the minimum distance found
22 return minDistance;
23}
24
Time and Space Complexity
Time Complexity: O(n)
, where n
is the length of the array nums
.
The code uses a generator expression with enumerate(nums)
which iterates through all elements in the array once. For each element, it checks if the value equals the target (constant time operation) and if so, calculates the absolute difference abs(i - start)
(also constant time). The min()
function then finds the minimum value from all calculated distances. In the worst case, all elements could equal the target, requiring us to compute distances for all n
elements. Therefore, the overall time complexity is O(n)
.
Space Complexity: O(1)
.
The generator expression (abs(i - start) for i, x in enumerate(nums) if x == target)
does not create a list to store all distances at once. Instead, it generates values one at a time as needed by the min()
function. The min()
function only needs to keep track of the current minimum value as it iterates through the generator, using constant extra space. No additional data structures proportional to the input size are created, resulting in O(1)
space complexity.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Empty Generator with min()
The most critical pitfall in this solution is assuming the generator expression will always produce at least one value. While the problem statement guarantees that the target exists in the array, if someone reuses this code without that guarantee, calling min()
on an empty generator will raise a ValueError
.
Problem Example:
nums = [1, 2, 3, 4, 5] target = 6 # doesn't exist start = 2 # This will raise: ValueError: min() arg is an empty sequence
Solution: Add a default value or handle the edge case explicitly:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
distances = [abs(i - start) for i, x in enumerate(nums) if x == target]
return min(distances) if distances else -1 # or float('inf') or None
2. Misunderstanding Distance Calculation
Developers might incorrectly calculate the distance without using absolute value, leading to negative distances being considered "minimum."
Problem Example:
# Incorrect: using (i - start) instead of abs(i - start)
return min(i - start for i, x in enumerate(nums) if x == target)
# If target is before start, this gives negative values
Solution:
Always use abs(i - start)
to ensure distances are positive.
3. Early Termination Optimization Missed
The current solution always scans the entire array. When the start index is near the beginning or end, we could optimize by expanding our search outward from the start position.
Problem Example:
nums = [1, 2, 3, 4, 5, 3, 7, 8, 9, 10, 11, 12, 13, 14, 15] target = 3 start = 0 # We'll scan all 15 elements even though answer is at index 2
Optimized Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
n = len(nums)
for distance in range(n):
# Check position to the left
if start - distance >= 0 and nums[start - distance] == target:
return distance
# Check position to the right
if start + distance < n and nums[start + distance] == target:
return distance
return -1 # Should never reach here given the guarantee
This optimization stops as soon as it finds the first occurrence of the target, which is guaranteed to be at minimum distance due to the expanding search pattern.
Which of the following problems can be solved with backtracking (select multiple)
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!