We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Minimum Distance to the Target Element

Number: 1975

Difficulty: Easy

Paid? No

Companies: Honeywell


Problem Description

Given an array of integers nums, a target value, and a start index, find an index i such that nums[i] equals target and the absolute difference |i - start| is minimized. Return this minimum absolute difference.


Key Insights

  • Since the target is guaranteed to exist in the array, a single linear scan is sufficient.
  • As you iterate, compute the absolute difference between the current index and the start index for each occurrence of target.
  • Maintain and update the minimum distance encountered during the scan.

Space and Time Complexity

Time Complexity: O(n), where n is the number of elements in nums. Space Complexity: O(1), as only a constant amount of extra space is used.


Solution

The solution involves iterating over the array to check for indices where the element equals the target. For each matching index, compute the absolute difference |i - start|. Track the minimum such difference found during the iteration. This straightforward approach leverages the guarantee that the target exists, ensuring that the algorithm is both simple and efficient.


Code Solutions

# Function to compute the minimum distance to the target element
def get_min_distance(nums, target, start):
    # Initialize min_distance with an infinitely large value
    min_distance = float('inf')
    
    # Iterate over each index and value in the list
    for index, value in enumerate(nums):
        # Check if the current element matches the target
        if value == target:
            # Update the minimum distance with the absolute difference
            min_distance = min(min_distance, abs(index - start))
    
    # Return the smallest absolute difference found
    return min_distance

# Example usage:
nums = [1,2,3,4,5]
target = 5
start = 3
print(get_min_distance(nums, target, start))  # Expected output: 1
← Back to All Questions