- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have one unsorted array A, and two numbers x and y. We have to find the minimum distance between x and y in A. The array can also contain duplicate elements. So if the array is A = [2, 5, 3, 5, 4, 4, 2, 3], x = 3 and y = 2, then the minimum distance between 3 and 2 is just 1.

To solve this, we have to follow these steps,

- Traverse the array from left to right and stop if either x or y has found. Then store the index of that position into prev
- Now traverse the array after the index prev, if the element with current index i matches with either x or y, then check if it is different from A[prev], if that is different, then update the min index if needed, if that are different, then update prev as prev := i

#include<iostream> using namespace std; int findMinDistance(int A[], int n, int x, int y) { int i = 0; int distance = INT_MAX; int prev_index; for (i = 0; i < n; i++) { if (A[i] == x || A[i] == y) { prev_index = i; break; } } while (i < n) { if (A[i] == x || A[i] == y) { if ( A[prev_index] != A[i] && (i - prev_index) < distance ){ distance = i - prev_index; prev_index = i; } else prev_index = i; } i++; } return distance; } int main() { int arr[] = {2, 5, 3, 5, 4, 4, 2, 3}; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; int y = 2; cout << "Minimum distance between " << x << " and " << y << " is: "<< findMinDistance(arr, n, x, y); }

Minimum distance between 3 and 2 is: 1

- Related Questions & Answers
- Program to find the minimum edit distance between two strings in C++
- Program to Find the Shortest Distance Between Two Points in C++
- Find the minimum difference between Shifted tables of two numbers in Python
- Find distance between two nodes of a Binary Tree in C++
- Find minimum difference between any two element in C++
- How to find minimum between 2 numbers using C#?
- Find the shortest distance between any pair of two different good nodes in C++
- Find distance between two nodes of a Binary Tree in C++ Program
- Digit distance of two numbers - JavaScript
- C program to calculate distance between two points
- Minimum Distance to Type a Word Using Two Fingers in C++
- Smallest Distance Between Two Words in Python
- Hamming Distance between two strings in JavaScript
- Program to find largest distance pair from two list of numbers in Python
- Program to find minimum distance to the target element using Python

Advertisements