# Maximum distance between two occurrences of same element in array

Given an array with repeated elements, the task is to find the maximum distance 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 array and find its **first** and **last** occurrence in array and take difference of first and last occurrence for maximum distance. Time complexity for this approach is O(n^{2}).

An **efficient solution** for this problem is to use hashing. The idea is to traverse input array and store index of first occurrence in a hash map. For every other occurrence, find the difference between index and the first index stored in hash map. If difference is more than 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<bits/stdc++.h> ` `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<n; i++) ` ` ` `{ ` ` ` `// If this is first occurrence of element, insert its ` ` ` `// index in map ` ` ` `if` `(mp.find(arr[i]) == mp.end()) ` ` ` `mp[arr[i]] = i; ` ` ` ` ` `// Else update max distance ` ` ` `else` ` ` `max_dist = max(max_dist, i - mp[arr[i]]); ` ` ` `} ` ` ` ` ` `return` `max_dist; ` `} ` ` ` `// Driver program to run the case ` `int` `main() ` `{ ` ` ` `int` `arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}; ` ` ` `int` `n = ` `sizeof` `(arr)/` `sizeof` `(arr[0]); ` ` ` `cout << maxDistance(arr, n); ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

## 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<Integer, Integer> 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 ` |

*chevron_right*

*filter_none*

## Python

`# 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 ` |

*chevron_right*

*filter_none*

## 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 ` |

*chevron_right*

*filter_none*

**Output:**

10

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

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

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

## Recommended Posts:

- Remove all occurrences of any element for maximum array sum
- Minimum distance between two occurrences of maximum
- Maximum element in an array such that its previous and next element product is maximum
- Sort integers in array according to their distance from the element K
- Missing occurrences of a number in an array such that maximum absolute difference of adjacent elements is minimum
- Maximum sum possible for a sub-sequence such that no two elements appear at a distance < K in the array
- Maximum distance between two 1s in a Binary Array in a given range
- Maximum possible remainder when an element is divided by other element in the array
- Sum of (maximum element - minimum element) for all the subsets of an array.
- Maximum sum in an array such that every element has exactly one adjacent element to it
- Type of array and its maximum element
- Find the maximum element in the array other than A
_{i} - Find the maximum possible value of last element of the Array
- Maximum possible GCD after replacing at most one element in the given array
- Find maximum sum taking every Kth element in the array
- Maximum number of multiples in an array before any element
- Find element with the maximum set bits in an array
- Maximum element in a sorted and rotated array
- Sum and Product of minimum and maximum element of an Array
- Maximum difference between first and last indexes of an element in array