LeetCode 1848: Minimum Distance to the Target Element Solution

Master LeetCode problem 1848 (Minimum Distance to the Target Element), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1848. Minimum Distance to the Target Element

Easy

Problem Explanation

Explanation

To solve this problem, we can iterate through the array nums and keep track of the minimum absolute different abs(i - start) whenever we encounter an element equal to the target. We initialize minDist to a large value and update it if a closer index to start is found.

Algorithm

  1. Initialize minDist to a large value.
  2. Iterate through the array nums.
  3. If nums[i] == target, calculate abs(i - start) and update minDist if the calculated value is smaller.
  4. Finally, return the value of minDist.

Time Complexity

The time complexity of this algorithm is O(n), where n is the number of elements in the input array nums.

Space Complexity

The space complexity is O(1) as we are using only a constant amount of extra space.

Solution Code

class Solution {
    public int getMinDistance(int[] nums, int target, int start) {
        int minDist = Integer.MAX_VALUE;
        
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                minDist = Math.min(minDist, Math.abs(i - start));
            }
        }
        
        return minDist;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1848 (Minimum Distance to the Target Element)?

This page provides optimized solutions for LeetCode problem 1848 (Minimum Distance to the Target Element) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1848 (Minimum Distance to the Target Element)?

The time complexity for LeetCode 1848 (Minimum Distance to the Target Element) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1848 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1848 in Java, C++, or Python.

Back to LeetCode Solutions