 Open in App
Not now

# Maximum distance between two occurrences of same element in array

• Difficulty Level : Easy
• Last Updated : 23 Mar, 2023

Given an array with repeated elements, the task is to find the maximum distance between two occurrences of an element.

Examples:

```Input : arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}
Output: 10
// maximum distance for 2 is 11-1 = 10
// maximum distance for 1 is 4-2 = 2
// maximum distance for 4 is 10-5 = 5  ```

A simple solution for this problem is to, one by one, pick each element from the array and find its first and last occurrence in the array and take the difference between the first and last occurrence for maximum distance. The time complexity for this approach is O(n2).

Below is the implementations of the idea.

## C++

 `// C++ program to find the maximum distance between` `// two equal elements` `#include `   `// function to find the maximum distance` `int` `maxDistance(``int` `arr[], ``int` `n)` `{`   `    ``// initialize the maxD to -1` `    ``int` `maxD = -1;` `    ``for` `(``int` `i = 0; i < n - 1; i++)` `        ``for` `(``int` `j = i + 1; j < n; j++)`   `            ``// check if two elements are equal` `            ``if` `(arr[i] == arr[j]) {` `                ``// if yes then calculate the distance and` `                ``// update maxD` `                ``int` `temp = ``abs``(j - i);` `                ``maxD = maxD > temp ? maxD : temp;` `            ``}` `    ``// return maximum distance` `    ``return` `maxD;` `}` `// Driver code` `int` `main()` `{` `    ``int` `Arr[] = { 1, 2, 4, 1, 3, 4, 2, 5, 6, 5 };` `    ``printf``(``"Maximum distance between two occurrences of "` `           ``"same element in array:%d"``,` `           ``maxDistance(Arr, 10));` `    ``return` `0;` `}`

## Java

 `import` `java.util.*;`   `public` `class` `Main {` `    ``// function to find the maximum distance` `    ``public` `static` `int` `maxDistance(``int``[] arr, ``int` `n)` `    ``{` `        ``// initialize the maxD to -1` `        ``int` `maxD = -``1``;` `        ``for` `(``int` `i = ``0``; i < n - ``1``; i++) {` `            ``for` `(``int` `j = i + ``1``; j < n; j++) {` `                ``// check if two elements are equal` `                ``if` `(arr[i] == arr[j]) {` `                    ``// if yes then calculate the distance` `                    ``// and update maxD` `                    ``int` `temp = Math.abs(j - i);` `                    ``maxD = maxD > temp ? maxD : temp;` `                ``}` `            ``}` `        ``}` `        ``// return maximum distance` `        ``return` `maxD;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int``[] Arr = { ``1``, ``2``, ``4``, ``1``, ``3``, ``4``, ``2``, ``5``, ``6``, ``5` `};` `        ``System.out.printf(` `            ``"Maximum distance between two occurrences of same element in array:%d"``,` `            ``maxDistance(Arr, ``10``));` `    ``}` `}`

Output

`Maximum distance between two occurrences of same element in array:5`

Time complexity : O(n2)
Auxiliary Space : O(n)

An efficient solution to this problem is to use hashing. The idea is to traverse the input array and store the index of the first occurrence in a hash map. For every other occurrence, find the difference between the index and the first index stored in the hash map. If the difference is more than the result so far, then update the result.

Below are implementations of the idea. The implementation uses unordered_map in

## C++

 `// C++ program to find maximum distance between two` `// same occurrences of a number.` `#include` `using` `namespace` `std;`   `// Function to find maximum distance between equal elements` `int` `maxDistance(``int` `arr[], ``int` `n)` `{` `    ``// Used to store element to first index mapping` `    ``unordered_map<``int``, ``int``> mp;`   `    ``// Traverse elements and find maximum distance between` `    ``// same occurrences with the help of map.` `    ``int` `max_dist = 0;` `    ``for` `(``int` `i=0; i

## Java

 `// Java program to find maximum distance between two ` `// same occurrences of a number.` `import` `java.io.*;` `import` `java.util.*;`   `class` `GFG ` `{`   `    ``// Function to find maximum distance between equal elements ` `    ``static` `int` `maxDistance(``int``[] arr, ``int` `n)` `    ``{` `        ``// Used to store element to first index mapping` `        ``HashMap map = ``new` `HashMap<>();` `        `  `        ``// Traverse elements and find maximum distance between ` `        ``// same occurrences with the help of map. ` `        ``int` `max_dist = ``0``;`   `        ``for` `(``int` `i = ``0``; i < n; i++)` `        ``{` `            ``// If this is first occurrence of element, insert its ` `            ``// index in map ` `            ``if` `(!map.containsKey(arr[i]))` `                ``map.put(arr[i], i);`   `            ``// Else update max distance ` `            ``else` `                ``max_dist = Math.max(max_dist, i - map.get(arr[i]));` `        ``}`   `        ``return` `max_dist;` `}`   `// Driver code` `public` `static` `void` `main(String args[])` `{` `    ``int``[] arr = {``3``, ``2``, ``1``, ``2``, ``1``, ``4``, ``5``, ``8``, ``6``, ``7``, ``4``, ``2``};` `    ``int` `n = arr.length;` `    ``System.out.println(maxDistance(arr, n));` `}` `} `   `// This code is contributed by rachana soma`

## Python3

 `# Python program to find maximum distance between two` `# same occurrences of a number.`   `# Function to find maximum distance between equal elements` `def` `maxDistance(arr, n):` `    `  `    ``# Used to store element to first index mapping` `    ``mp ``=` `{}`   `    ``# Traverse elements and find maximum distance between` `    ``# same occurrences with the help of map.` `    ``maxDict ``=` `0` `    ``for` `i ``in` `range``(n):`   `        ``# If this is first occurrence of element, insert its` `        ``# index in map` `        ``if` `arr[i] ``not` `in` `mp.keys():` `            ``mp[arr[i]] ``=` `i`   `        ``# Else update max distance` `        ``else``:` `            ``maxDict ``=` `max``(maxDict, i``-``mp[arr[i]])`   `    ``return` `maxDict`   `# Driver Program` `if` `__name__``=``=``'__main__'``:` `    ``arr ``=` `[``3``, ``2``, ``1``, ``2``, ``1``, ``4``, ``5``, ``8``, ``6``, ``7``, ``4``, ``2``]` `    ``n ``=` `len``(arr)` `    ``print` `(maxDistance(arr, n))` `        `  `# Contributed By: Harshit Sidhwa`

## C#

 `// C# program to find maximum distance between two ` `// same occurrences of a number.`   `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG ` `{`   `    ``// Function to find maximum distance between equal elements ` `    ``static` `int` `maxDistance(``int``[] arr, ``int` `n)` `    ``{` `        ``// Used to store element to first index mapping` `        ``Dictionary<``int``, ``int``> map = ``new` `Dictionary<``int``, ``int``>();` `        `  `        ``// Traverse elements and find maximum distance between ` `        ``// same occurrences with the help of map. ` `        ``int` `max_dist = 0;`   `        ``for` `(``int` `i = 0; i < n; i++)` `        ``{` `            ``// If this is first occurrence of element, insert its ` `            ``// index in map ` `            ``if` `(!map.ContainsKey(arr[i]))` `                ``map.Add(arr[i], i);`   `            ``// Else update max distance ` `            ``else` `                ``max_dist = Math.Max(max_dist, i - map[arr[i]]);` `        ``}`   `        ``return` `max_dist;` `}`   `// Driver code` `public` `static` `void` `Main(String []args)` `{` `    ``int``[] arr = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2};` `    ``int` `n = arr.Length;` `    ``Console.WriteLine(maxDistance(arr, n));` `}` `}`   `// This code is contributed by PrinciRaj1992`

## Javascript

 ``

Output

`10`

Time complexity : O(n) under the assumption that unordered_map’s search and insert operations take O(1) time.
Auxiliary Space : O(n).

This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

My Personal Notes arrow_drop_up
Related Articles