VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-distance-two-occurrences-element-array/

⇱ Max Distance Between Two Occurrences - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Max Distance Between Two Occurrences

Last Updated : 23 Jul, 2025

Given an array arr[], the task is to find the maximum distance between two occurrences of any element. If no element occurs twice, return 0.

Examples: 

Input: arr = [1, 1, 2, 2, 2, 1]
Output: 5
Explanation: distance for 1 is: 5-0 = 5, distance for 2 is: 4-2 = 2, So max distance is 5.

Input : arr[] = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2]
Output: 10
Explanation : Max distance for 2 is 11-1 = 10, max distance for 1 is 4-2 = 2 and max distance for 4 is 10-5 = 5

Input: arr[] = [1, 2, 3, 6, 5, 4]
Output: 0
Explanation: No element has two occurrence, so maximum distance = 0.

[Naive Approach] Exploring all pairs - O(n^2) Time and O(1) Space

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.


Output
5

[Expected Approach] Using Hash Map or Dictionary - O(n) Time and O(n) Space

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.


Output
5
Comment
Article Tags: