Minimum distance between any two equal elements in an Array
Given an array arr, the task is to find the minimum distance between any two same elements in the array. If no such element is found, return -1.
Examples:
Input: arr = {1, 2, 3, 2, 1}
Output: 2
Explanation:
There are two matching pairs of values: 1 and 2 in this array.
Minimum Distance between two 1’s = 4
Minimum Distance between two 2’s = 2
Therefore, Minimum distance between any two equal elements in the Array = 2
Input: arr = {3, 5, 4, 6, 5, 3}
Output: 3
Explanation:
There are two matching pairs of values: 3 and 5 in this array.
Minimum Distance between two 3’s = 5
Minimum Distance between two 5’s = 3
Therefore, Minimum distance between any two equal elements in the Array = 3
Naive Approach: The simplest approach is using two nested for loops to form each and every combination. If the elements are equal, find the minimum distance.
Time complexity: O(N2)
Efficient Approach: An efficient approach for this problem is to use map to store array elements as a key and their index as the values.
Below is the step by step algorithm:
- Traverse the array one by one.
- Check if this element is in the map or not.
- If the map does not contain this element, insert it as (element, current index) pair.
- If the array element present in the map, fetch the previous index of this element from the map.
- Find the difference between the previous index and the current index
- Compare each difference and find the minimum distance.
- If no such element found, return -1.
Below is the implementation of the above approach.
C++
#include<bits/stdc++.h>
using namespace std;
int minimumDistance( int a[], int n)
{
map< int , int > hmap;
int minDistance = INT_MAX;
int previousIndex = 0, currentIndex = 0;
for ( int i = 0; i < n; i++) {
if (hmap.find(a[i])!=hmap.end()) {
currentIndex = i;
previousIndex = hmap[a[i]];
minDistance = min((currentIndex -
previousIndex),minDistance);
}
hmap[a[i]] = i;
}
return (minDistance == INT_MAX ? -1 : minDistance);
}
int main()
{
int a1[] = { 1, 2, 3, 2, 1 };
int n = sizeof (a1)/ sizeof (a1[0]);
cout << minimumDistance(a1, n) << endl;
int a2[] = { 3, 5, 4, 6, 5, 3 };
n = sizeof (a2)/ sizeof (a2[0]);
cout << minimumDistance(a2, n) << endl;
int a3[] = { 1, 2, 1, 4, 1 };
n = sizeof (a3)/ sizeof (a3[0]);
cout << minimumDistance(a3, n) << endl;
}
|
Java
import java.util.*;
import java.math.*;
class GFG {
static int minimumDistance( int [] a)
{
HashMap<Integer, Integer> hmap
= new HashMap<>();
int minDistance = Integer.MAX_VALUE;
int previousIndex = 0 , currentIndex = 0 ;
for ( int i = 0 ; i < a.length; i++) {
if (hmap.containsKey(a[i])) {
currentIndex = i;
previousIndex = hmap.get(a[i]);
minDistance
= Math.min(
(currentIndex - previousIndex),
minDistance);
}
hmap.put(a[i], i);
}
return (
minDistance == Integer.MAX_VALUE
? - 1
: minDistance);
}
public static void main(String args[])
{
int a1[] = { 1 , 2 , 3 , 2 , 1 };
System.out.println(minimumDistance(a1));
int a2[] = { 3 , 5 , 4 , 6 , 5 , 3 };
System.out.println(minimumDistance(a2));
int a3[] = { 1 , 2 , 1 , 4 , 1 };
System.out.println(minimumDistance(a3));
}
}
|
Python3
def minimumDistance(a):
hmap = dict ()
minDistance = 10 * * 9
previousIndex = 0
currentIndex = 0
for i in range ( len (a)):
if a[i] in hmap:
currentIndex = i
previousIndex = hmap[a[i]]
minDistance = min ((currentIndex -
previousIndex), minDistance)
hmap[a[i]] = i
if minDistance = = 10 * * 9 :
return - 1
return minDistance
if __name__ = = '__main__' :
a1 = [ 1 , 2 , 3 , 2 , 1 ]
print (minimumDistance(a1))
a2 = [ 3 , 5 , 4 , 6 , 5 , 3 ]
print (minimumDistance(a2))
a3 = [ 1 , 2 , 1 , 4 , 1 ]
print (minimumDistance(a3))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int minimumDistance( int [] a)
{
Dictionary< int ,
int > hmap = new Dictionary< int ,
int >();
int minDistance = Int32.MaxValue;
int previousIndex = 0, currentIndex = 0;
for ( int i = 0; i < a.Length; i++)
{
if (hmap.ContainsKey(a[i]))
{
currentIndex = i;
previousIndex = hmap[a[i]];
minDistance = Math.Min((currentIndex -
previousIndex),
minDistance);
}
if (!hmap.ContainsKey(a[i]))
hmap.Add(a[i], i);
else
hmap[a[i]] = i;
}
return (minDistance == Int32.MaxValue ?
-1 : minDistance);
}
static public void Main()
{
int [] a1 = { 1, 2, 3, 2, 1 };
Console.WriteLine(minimumDistance(a1));
int [] a2 = { 3, 5, 4, 6, 5, 3 };
Console.WriteLine(minimumDistance(a2));
int [] a3 = { 1, 2, 1, 4, 1 };
Console.WriteLine(minimumDistance(a3));
}
}
|
Javascript
<script>
function minimumDistance(a, n)
{
var hmap = new Map();
var minDistance = 1000000000;
var previousIndex = 0, currentIndex = 0;
for ( var i = 0; i < n; i++) {
if (hmap.has(a[i])) {
currentIndex = i;
previousIndex = hmap.get(a[i]);
minDistance = Math.min((currentIndex -
previousIndex),minDistance);
}
hmap.set(a[i], i);
}
return (minDistance == 1000000000 ? -1 : minDistance);
}
var a1 = [1, 2, 3, 2, 1];
var n = a1.length;
document.write( minimumDistance(a1, n) + "<br>" );
var a2 = [3, 5, 4, 6, 5, 3];
n = a2.length;
document.write( minimumDistance(a2, n) + "<br>" );
var a3 = [1, 2, 1, 4, 1];
n = a3.length;
document.write( minimumDistance(a3, n));
</script>
|
Time complexity: O(N)
Auxiliary Space: O(N)
Approach 2: Using a Two-Pointer Approach
In this approach, we can use two pointers to keep track of the indices of two equal elements that are farthest apart. We can start with two pointers pointing to the first occurrence of each element in the array, and then move the pointers closer together until we find a pair of equal elements with the maximum distance between them.
One approach to find the minimum distance between any two equal elements in an array is to compare each element with all the other elements of the array to find the minimum distance. The minimum distance will be the minimum index difference between two equal elements. We can iterate over the array and for each element, we can search for the same element in the remaining array and find the minimum distance. We can then return the minimum distance as the output.
Algorithm:
- Initialize a variable min_dist with a very large value.
- Iterate through the array from 0 to n-1.
- For each element arr[i], iterate through the array from i+1 to n-1.
- If the same element is found at arr[j], calculate the distance between the two elements as j-i and store it in a temporary variable.
- If this distance is less than the current value of min_dist, update min_dist to this distance.
- After iterating through all the elements, return the value of min_dist.
Here’s the code:
C++
#include <iostream>
#include <climits>
#include <vector>
using namespace std;
int minDistance(vector< int >& arr) {
int min_dist = INT_MAX;
for ( int i = 0; i < arr.size(); i++) {
for ( int j = i+1; j < arr.size(); j++) {
if (arr[i] == arr[j]) {
min_dist = min(min_dist, j - i);
}
}
}
return min_dist == INT_MAX ? -1 : min_dist;
}
int main() {
vector< int > arr1 = { 1, 2, 3, 2, 1 };
cout << minDistance(arr1) << endl;
vector< int > arr2 = { 3, 5, 4, 6, 5, 3 };
cout << minDistance(arr2) << endl;
vector< int > arr3 = { 1, 2, 1, 4, 1 };
cout << minDistance(arr3) << endl;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static int minDistance(List<Integer> arr) {
int min_dist = Integer.MAX_VALUE;
for ( int i = 0 ; i < arr.size(); i++) {
for ( int j = i+ 1 ; j < arr.size(); j++) {
if (arr.get(i).equals(arr.get(j))) {
min_dist = Math.min(min_dist, j - i);
}
}
}
return min_dist == Integer.MAX_VALUE ? - 1 : min_dist;
}
public static void main(String[] args) {
List<Integer> arr1 = Arrays.asList( 1 , 2 , 3 , 2 , 1 );
System.out.println(minDistance(arr1));
List<Integer> arr2 = Arrays.asList( 3 , 5 , 4 , 6 , 5 , 3 );
System.out.println(minDistance(arr2));
List<Integer> arr3 = Arrays.asList( 1 , 2 , 1 , 4 , 1 );
System.out.println(minDistance(arr3));
}
}
|
Python3
def min_distance(arr):
min_dist = float ( 'inf' )
for i in range ( len (arr)):
for j in range (i + 1 , len (arr)):
if arr[i] = = arr[j]:
min_dist = min (min_dist, j - i)
return - 1 if min_dist = = float ( 'inf' ) else min_dist
arr1 = [ 1 , 2 , 3 , 2 , 1 ]
print (min_distance(arr1))
arr2 = [ 3 , 5 , 4 , 6 , 5 , 3 ]
print (min_distance(arr2))
arr3 = [ 1 , 2 , 1 , 4 , 1 ]
print (min_distance(arr3))
|
C#
using System;
using System.Collections.Generic;
class Program {
static int MinDistance(List< int > arr)
{
int minDist = int .MaxValue;
for ( int i = 0; i < arr.Count; i++) {
for ( int j = i + 1; j < arr.Count; j++) {
if (arr[i] == arr[j]) {
minDist = Math.Min(minDist, j - i);
}
}
}
return minDist == int .MaxValue ? -1 : minDist;
}
static void Main( string [] args)
{
List< int > arr1 = new List< int >{ 1, 2, 3, 2, 1 };
Console.WriteLine(MinDistance(arr1));
List< int > arr2 = new List< int >{ 3, 5, 4, 6, 5, 3 };
Console.WriteLine(MinDistance(arr2));
List< int > arr3 = new List< int >{ 1, 2, 1, 4, 1 };
Console.WriteLine(MinDistance(arr3));
}
}
|
Javascript
function minDistance(arr) {
let minDist = Number.MAX_VALUE;
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
minDist = Math.min(minDist, j - i);
}
}
}
return minDist === Number.MAX_VALUE ? -1 : minDist;
}
let arr1 = [1, 2, 3, 2, 1];
console.log(minDistance(arr1));
let arr2 = [3, 5, 4, 6, 5, 3];
console.log(minDistance(arr2));
let arr3 = [1, 2, 1, 4, 1];
console.log(minDistance(arr3));
|
Time complexity:O(n^2)
Auxiliary Space: O(1)
Last Updated :
20 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...