
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 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
Advertisements