Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
#includeusing 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 Output
Minimum distance between 3 and 2 is: 1
Advertisements
