Similar Problems

Similar Problems not available

Minimum Distance To The Target Element - Leetcode Solution

Companies:

LeetCode:  Minimum Distance To The Target Element Leetcode Solution

Difficulty: Easy

Topics: array  

The Minimum Distance To The Target Element problem on leetcode can be solved using a simple linear search algorithm. The problem can be described as finding the minimum distance between a target element and any other element in a given array.

To solve this problem, we need to loop through the array and calculate the distance between the target element and each element in the array. We then update a variable with the minimum distance found so far. Here's the step-by-step solution:

Step 1: Initialize minimum distance to a large value, e.g. Infinity.

let minDist = Infinity;

Step 2: Loop through the array and check the distance between the current element and the target element.

for (let i = 0; i < arr.length; i++) {
  let dist = Math.abs(i - targetIndex);
  if (arr[i] === target && dist < minDist) {
      minDist = dist;
  }
}

Step 3: Return the minimum distance.

return minDist;

The complete solution looks like this:

var getMinDistance = function(nums, target, start) {
    let minDist = Infinity;
    for (let i = 0; i < nums.length; i++) {
        let dist = Math.abs(i - start);
        if (nums[i] === target && dist < minDist) {
            minDist = dist;
        }
    }
    return minDist;
};

This solution has O(n) time complexity, where n is the length of the input array. This is because we are only looping through the array once. The space complexity of this solution is O(1) as we are only using a few variables.

Minimum Distance To The Target Element Solution Code

1