Related Articles

# Minimum distance between any two equal elements in an Array

• Difficulty Level : Hard
• Last Updated : 15 Jun, 2021

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:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr = {1, 2, 3, 2, 1}
Output:
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:
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:

1. Traverse the array one by one.
2. 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.
3. Find the difference between the previous index and the current index
4. Compare each difference and find the minimum distance.
5. If no such element found, return -1.

Below is the implementation of the above approach.

## C++

 `// C++ program to find the minimum distance``// between two occurrences of the same element``#include``using` `namespace` `std;` `// Function to find the minimum``// distance between the same elements``int` `minimumDistance(``int` `a[], ``int` `n)``{` `    ``// Create a HashMap to``    ``// store (key, values) pair.``    ``map<``int``,``int``> hmap;` `    ``int` `minDistance = INT_MAX;` `    ``// Initialize previousIndex``    ``// and currentIndex as 0``    ``int` `previousIndex = 0, currentIndex = 0;` `    ``// Traverse the array and``    ``// find the minimum distance``    ``// between the same elements with map` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``if` `(hmap.find(a[i])!=hmap.end()) {``            ``currentIndex = i;` `            ``// Fetch the previous index from map.``            ``previousIndex = hmap[a[i]];` `            ``// Find the minimum distance.``            ``minDistance = min((currentIndex -``                        ``previousIndex),minDistance);``        ``}` `        ``// Update the map.``        ``hmap[a[i]] = i;``    ``}` `    ``// return minimum distance,``    ``// if no such elements found, return -1``    ``return` `(minDistance == INT_MAX ? -1 : minDistance);``}` `// Driver code``int` `main()``{` `    ``// Test Case 1:``    ``int` `a1[] = { 1, 2, 3, 2, 1 };``    ``int` `n = ``sizeof``(a1)/``sizeof``(a1);` `    ``cout << minimumDistance(a1, n) << endl;` `    ``// Test Case 2:``    ``int` `a2[] = { 3, 5, 4, 6, 5, 3 };``    ``n = ``sizeof``(a2)/``sizeof``(a2);``    ``cout << minimumDistance(a2, n) << endl;` `    ``// Test Case 3:``    ``int` `a3[] = { 1, 2, 1, 4, 1 };``    ``n = ``sizeof``(a3)/``sizeof``(a3);` `    ``cout << minimumDistance(a3, n) << endl;``}` `// This code is contributed by Sanjit_Prasad`

## Java

 `// Java program to find the minimum distance``// between two occurrences of the same element` `import` `java.util.*;``import` `java.math.*;` `class` `GFG {` `    ``// Function to find the minimum``    ``// distance between the same elements``    ``static` `int` `minimumDistance(``int``[] a)``    ``{` `        ``// Create a HashMap to``        ``// store (key, values) pair.``        ``HashMap hmap``            ``= ``new` `HashMap<>();``        ``int` `minDistance = Integer.MAX_VALUE;` `        ``// Initialize previousIndex``        ``// and currentIndex as 0``        ``int` `previousIndex = ``0``, currentIndex = ``0``;` `        ``// Traverse the array and``        ``// find the minimum distance``        ``// between the same elements with map``        ``for` `(``int` `i = ``0``; i < a.length; i++) {` `            ``if` `(hmap.containsKey(a[i])) {``                ``currentIndex = i;` `                ``// Fetch the previous index from map.``                ``previousIndex = hmap.get(a[i]);` `                ``// Find the minimum distance.``                ``minDistance``                    ``= Math.min(``                        ``(currentIndex - previousIndex),``                        ``minDistance);``            ``}` `            ``// Update the map.``            ``hmap.put(a[i], i);``        ``}` `        ``// return minimum distance,``        ``// if no such elements found, return -1``        ``return` `(``            ``minDistance == Integer.MAX_VALUE``                ``? -``1``                ``: minDistance);``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String args[])``    ``{` `        ``// Test Case 1:``        ``int` `a1[] = { ``1``, ``2``, ``3``, ``2``, ``1` `};``        ``System.out.println(minimumDistance(a1));` `        ``// Test Case 2:``        ``int` `a2[] = { ``3``, ``5``, ``4``, ``6``, ``5``, ``3` `};``        ``System.out.println(minimumDistance(a2));` `        ``// Test Case 3:``        ``int` `a3[] = { ``1``, ``2``, ``1``, ``4``, ``1` `};``        ``System.out.println(minimumDistance(a3));``    ``}``}`

## Python3

 `# Python3 program to find the minimum distance``# between two occurrences of the same element` `# Function to find the minimum``# distance between the same elements``def` `minimumDistance(a):` `    ``# Create a HashMap to``    ``# store (key, values) pair.``    ``hmap ``=` `dict``()``    ``minDistance ``=` `10``*``*``9` `    ``# Initialize previousIndex``    ``# and currentIndex as 0``    ``previousIndex ``=` `0``    ``currentIndex ``=` `0` `    ``# Traverse the array and``    ``# find the minimum distance``    ``# between the same elements with map``    ``for` `i ``in` `range``(``len``(a)):` `        ``if` `a[i] ``in` `hmap:``            ``currentIndex ``=` `i` `            ``# Fetch the previous index from map.``            ``previousIndex ``=` `hmap[a[i]]` `            ``# Find the minimum distance.``            ``minDistance ``=` `min``((currentIndex ``-``                        ``previousIndex), minDistance)` `        ``# Update the map.``        ``hmap[a[i]] ``=` `i` `    ``# return minimum distance,``    ``# if no such elements found, return -1``    ``if` `minDistance ``=``=` `10``*``*``9``:``        ``return` `-``1``    ``return` `minDistance` `# Driver code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ``# Test Case 1:``    ``a1 ``=` `[``1``, ``2``, ``3``, ``2``, ``1` `]``    ``print``(minimumDistance(a1))` `    ``# Test Case 2:``    ``a2 ``=` `[``3``, ``5``, ``4``, ``6``, ``5``,``3``]``    ``print``(minimumDistance(a2))` `    ``# Test Case 3:``    ``a3 ``=` `[``1``, ``2``, ``1``, ``4``, ``1` `]``    ``print``(minimumDistance(a3))``    ` `# This code is contributed by mohit kumar 29   `

## C#

 `// C# program to find the minimum distance``// between two occurrences of the same element``using` `System;``using` `System.Collections.Generic;` `class` `GFG{``    ` `// Function to find the minimum``// distance between the same elements``static` `int` `minimumDistance(``int``[] a)``{``    ` `    ``// Create a HashMap to``    ``// store (key, values) pair.``    ``Dictionary<``int``,``               ``int``> hmap = ``new` `Dictionary<``int``,``                                          ``int``>();``    ``int` `minDistance = Int32.MaxValue;` `    ``// Initialize previousIndex``    ``// and currentIndex as 0``    ``int` `previousIndex = 0, currentIndex = 0;` `    ``// Traverse the array and``    ``// find the minimum distance``    ``// between the same elements with map``    ``for``(``int` `i = 0; i < a.Length; i++)``    ``{``        ``if` `(hmap.ContainsKey(a[i]))``        ``{``            ``currentIndex = i;``            ` `            ``// Fetch the previous index from map.``            ``previousIndex = hmap[a[i]];` `            ``// Find the minimum distance.``            ``minDistance = Math.Min((currentIndex -``                                    ``previousIndex),``                                    ``minDistance);``        ``}` `        ``// Update the map.``        ``if` `(!hmap.ContainsKey(a[i]))``            ``hmap.Add(a[i], i);``        ``else``            ``hmap[a[i]] = i;``    ``}` `    ``// Return minimum distance,``    ``// if no such elements found, return -1``    ``return``(minDistance == Int32.MaxValue ?``                    ``-1 : minDistance);``}` `// Driver code``static` `public` `void` `Main()``{``    ` `    ``// Test Case 1:``    ``int``[] a1 = { 1, 2, 3, 2, 1 };``    ``Console.WriteLine(minimumDistance(a1));``    ` `    ``// Test Case 2:``    ``int``[] a2 = { 3, 5, 4, 6, 5, 3 };``    ``Console.WriteLine(minimumDistance(a2));``    ` `    ``// Test Case 3:``    ``int``[] a3 = { 1, 2, 1, 4, 1 };``    ``Console.WriteLine(minimumDistance(a3));``}``}` `// This code is contributed by unknown2108`

## Javascript

 ``
Output:
```2
3
2```

Time complexity: O(N)

My Personal Notes arrow_drop_up