Minimum distance between any two equal elements in an Array
Last Updated :
12 Jul, 2025
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++
// C++ program to find the minimum distance
// between two occurrences of the same element
#include<bits/stdc++.h>
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[0]);
cout << minimumDistance(a1, n) << endl;
// Test Case 2:
int a2[] = { 3, 5, 4, 6, 5, 3 };
n = sizeof(a2)/sizeof(a2[0]);
cout << minimumDistance(a2, n) << endl;
// Test Case 3:
int a3[] = { 1, 2, 1, 4, 1 };
n = sizeof(a3)/sizeof(a3[0]);
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<Integer, Integer> 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
<script>
// Javascript program to find the minimum distance
// between two occurrences of the same element
// Function to find the minimum
// distance between the same elements
function minimumDistance(a, n)
{
// Create a HashMap to
// store (key, values) pair.
var hmap = new Map();
var minDistance = 1000000000;
// Initialize previousIndex
// and currentIndex as 0
var previousIndex = 0, currentIndex = 0;
// Traverse the array and
// find the minimum distance
// between the same elements with map
for (var i = 0; i < n; i++) {
if (hmap.has(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.set(a[i], i);
}
// return minimum distance,
// if no such elements found, return -1
return (minDistance == 1000000000 ? -1 : minDistance);
}
// Driver code
// Test Case 1:
var a1 = [1, 2, 3, 2, 1];
var n = a1.length;
document.write( minimumDistance(a1, n) + "<br>");
// Test Case 2:
var a2 = [3, 5, 4, 6, 5, 3];
n = a2.length;
document.write( minimumDistance(a2, n) + "<br>");
// Test Case 3:
var a3 = [1, 2, 1, 4, 1];
n = a3.length;
document.write( minimumDistance(a3, n));
// This code is contributed by famously.
</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; // Output: 3
vector<int> arr2 = { 3, 5, 4, 6, 5, 3 };
cout << minDistance(arr2) << endl; // Output: 3
vector<int> arr3 = { 1, 2, 1, 4, 1 };
cout << minDistance(arr3) << endl; // Output: 3
return 0;
}
Java
/*package whatever //do not write package name here */
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)); // Output: 3
List<Integer> arr2 = Arrays.asList(3, 5, 4, 6, 5, 3);
System.out.println(minDistance(arr2)); // Output: 3
List<Integer> arr3 = Arrays.asList(1, 2, 1, 4, 1);
System.out.println(minDistance(arr3)); // Output: 3
}
}
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)) # Output: 3
arr2 = [3, 5, 4, 6, 5, 3]
print(min_distance(arr2)) # Output: 3
arr3 = [1, 2, 1, 4, 1]
print(min_distance(arr3)) # Output: 3
C#
using System;
using System.Collections.Generic;
class Program {
// Function to find the minimum distance between two
// equal elements in an array
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)
{
// Sample inputs
List<int> arr1 = new List<int>{ 1, 2, 3, 2, 1 };
Console.WriteLine(MinDistance(arr1)); // Output: 3
List<int> arr2 = new List<int>{ 3, 5, 4, 6, 5, 3 };
Console.WriteLine(MinDistance(arr2)); // Output: 3
List<int> arr3 = new List<int>{ 1, 2, 1, 4, 1 };
Console.WriteLine(MinDistance(arr3)); // Output: 3
}
}
// This code is contributed by user_dtewbxkn77n
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;
}
// Sample inputs
let arr1 = [1, 2, 3, 2, 1];
console.log(minDistance(arr1)); // Output: 3
let arr2 = [3, 5, 4, 6, 5, 3];
console.log(minDistance(arr2)); // Output: 3
let arr3 = [1, 2, 1, 4, 1];
console.log(minDistance(arr3)); // Output: 3
Time complexity:O(n^2)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem