Jobs
Interviews

Solve Minimum Distance in an Array using Python Language

Solve Minimum Distance in an Array using Python to enhance your skills with python 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

Interactive Exercises Practice coding with problems designed for beginners and experts.

Step-by-Step Solutions Understand every step of the solution process.

Real-World Scenarios Apply your skills to real-world problems and boost your confidence.

Choose from the following categories