← Back to DSA
#1848

Minimum Distance to the Target Element

Minimum Distance to the Target Element solution for LeetCode 1848, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.

Easy
Array
Solve on LeetCode ↗

Minimum Distance to the Target Element

Intuition

We only care about indices where nums[i] == target.

For every such index i, the cost is:

abs(i - start)

So the problem becomes very direct:

  • scan the array once
  • whenever we see target, compute its distance from start
  • keep the minimum distance seen so far

Because the problem guarantees that target exists in nums, we are sure we will find at least one valid answer.

Approach: Simulation

We use a variable answer to store the minimum distance.

Initialize it with nums.length, which is safely larger than or equal to any valid answer because:

  • the farthest possible distance between two indices in the array is nums.length - 1

Then traverse the array:

  1. If nums[index] is not equal to target, skip it
  2. If it is equal to target, compute abs(index - start)
  3. Update answer with the smaller value

At the end, answer is the minimum distance to the target element.

Code Solution

Switch between languages

class Solution {
    public int getMinDistance(int[] nums, int target, int start) {
        int answer = nums.length;

        for (int index = 0; index < nums.length; index++) {
            if (nums[index] == target) {
                answer = Math.min(answer, Math.abs(index - start));
            }
        }

        return answer;
    }
}

Dry run

Take:

nums = [1, 2, 3, 4, 5]
target = 5
start = 3

We scan from left to right:

  • index 0, value 1 -> not target
  • index 1, value 2 -> not target
  • index 2, value 3 -> not target
  • index 3, value 4 -> not target
  • index 4, value 5 -> target found

Now compute:

abs(4 - 3) = 1

So the minimum distance is 1.

Why this works

Every valid answer must come from some index where the value equals target.

Our loop checks all such indices exactly once and calculates their distance from start. Since we keep the smallest of all these distances, the final value is the minimum possible answer.

Complexity Analysis

Time Complexity: O(n)

  • we traverse the array once

Space Complexity: O(1)

  • we only use a constant amount of extra space

Common mistake

Some people try to search outward from start in both directions.

That can also work, but for this problem a full linear scan is simpler and already optimal enough for the given constraints.

Dynamic Programming

7 DP Patterns > 100 LeetCode Questions

Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.

7 patternsProgress tracking
Read 7 patterns (5 min)