- 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

# Find the minimum distance between two numbers in C++

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

## Example

#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); }

## Output

Minimum distance between 3 and 2 is: 1

- Related Questions & Answers
- Program to find the minimum edit distance between two strings in C++
- Find the minimum difference between Shifted tables of two numbers in Python
- Program to Find the Shortest Distance Between Two Points in C++
- Digit distance of two numbers - JavaScript
- Find distance between two nodes of a Binary Tree in C++
- Program to find minimum distance of two given words in a text in Python
- Smallest Distance Between Two Words in Python
- Hamming Distance between two strings in JavaScript
- Find minimum difference between any two element in C++
- Program to find minimum total distance between house and nearest mailbox in Python
- Program to find largest distance pair from two list of numbers in Python
- Find the shortest distance between any pair of two different good nodes in C++
- How to find minimum between 2 numbers using C#?
- Find distance between two nodes of a Binary Tree in C++ Program
- C++ program to find minimum difference between the sums of two subsets from first n natural numbers

Advertisements