Jobs
Interviews

Solve Minimum Distance in an Array using JavaScript Language

Solve Minimum Distance in an Array using JavaScript to enhance your skills with javascript coding practice , master coding concepts, and prepare for interviews with practical exercises and detailed solutions.

Minimum Distance in an Array

Difficulty : Easy

Categories :

  • Arrays

Given an array arr[] and two distinct elements x and y, find the minimum index-based distance between x and y in the array. Return -1 if either x or y does not exist in the array.

The distance between two elements in an array is the absolute difference between their indices.

Constraints:

  • 1 ≤ arr.length ≤ 105
  • 0 ≤ arr[i], x, y ≤ 105
  • x ≠ y

Examples:

Input: arr = [1,2,3,2], x = 1, y = 2
Output: 1
Explanation: x = 1 is at index 0 and y = 2 is at index 1. The minimum distance between them is 1.
Input: arr = [86,39,90,67,84,66,62], x = 42, y = 12
Output: -1
Explanation: Either x = 42 or y = 12 is not present in the array.
Input: arr = [10,20,30,40,50], x = 10, y = 50
Output: 4
Explanation: x = 10 is at index 0 and y = 50 is at index 4. The distance between them is 4.

Follow-up:

Can you solve it with O(n) time complexity and O(1) space complexity?

Problem Solving

Input

What You'll Find Here

Hands-On Exercises Work on coding problems inspired by real-world scenarios.

Detailed Explanations Break down complex solutions into easy-to-understand steps.

Interactive Learning Test your skills in an engaging and fun way.

Choose from the following categories