DDSA Solutions

1848. Minimum Distance to the Target Element

Time: O(n)
Space: O(1)

Problem Overview

Minimum Distance to the Target Element (Unknown) asks you to solve a structured algorithmic task. Scan the array once. Track the minimum distance from start to any occurrence

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

Scan the array once. Track the minimum distance from start to any occurrence

of target by checking |i - start| for each matching element.

1848.cs
C#
// Approach: Scan the array once. Track the minimum distance from start to any occurrence
// of target by checking |i - start| for each matching element.
// Time: O(n) Space: O(1)
public class Solution
{
    public int GetMinDistance(int[] nums, int target, int start)
    {
        int ans = int.MaxValue;

        for (int i = 0; i < nums.Length; ++i)
        {
            if (nums[i] == target)
                ans = Math.Min(ans, Math.Abs(i - start));
        }

        return ans;
    }
}
Was this solution helpful?