Max distance between same elements | Practice | GeeksforGeeks

Given an array with repeated elements, the task is to find the maximum distance between two occurrences of an element.
Example 1:
Input
n= 6
arr = {1, 1, 2, 2, 2, 1}

Output
5

Explanation
arr[] = {1, 1, 2, 2, 2, 1}
Max Distance: 5
Distance for 1 is: 5-0 = 5
Distance for 2 is : 4-2 = 2
Max Distance 5
Example 2:
Input
n = 12
arr = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}

Output
10

Explanation



arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}
Max Distance 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
Your Task:
Complete maxDistance() function which takes both the given array and their size as function arguments and returns the maximum distance between 2 same elements. 

Expected Time Complexity : O(N)
Expected Auxilliary Space : O(N)
Constraints:
1<=N<=106
 
 
0
subhamsen11 day ago
Python code
def maxDistance(self, arr, n):    # declaure a default dict with list    # add the all the index as a list to value of dictionary    #now make the dictionary with key as arr elemt and list of indexes as value    # traverse the dictionary and add the distance of each element to a result value[-1] last element and [0] first index    #    from collections import defaultdict    new=defaultdict(list)    for index,value in enumerate(arr):        new[value].append(index)    # now lets get the max distance  #    res=[]    for key,value in new.items():        distance=value[-1]-value[0] # calculating distance        res.append(distance)   # print(max(res))    return max(res)
+1
tanashah3 days ago
unordered_map<int,int>mp;
       int max_count=0;
       for(int i=0;i<n;i++){
          if(mp.find(arr[i])==mp.end()){
              mp[arr[i]]=i;
          }else{
              max_count=max(max_count,i-mp[arr[i]]);
          }
       }
       return max_count;//T.C O(N) only
0
shailendramaheshwari173 weeks ago
 int maxDistance(int arr[], int n)
   {
   int a[n] , max_d = -1;
   fill(a,a+n,-1);
   for(int i=0;i<n;i++)
   {
       int temp = arr[i];
       if(((arr[0] != arr[1])&&(n==2))|| n==1) return 0;
       else
       if(a[temp] >-1) {
           max_d = max(max_d,i-a[temp]);
       }
       else
           a[temp] = i;
   }
   return max_d;
   }
0
ajayab77991 month ago
class Solution
{
    int maxDistance(int arr[], int n)
    {
	// Your code here
	    HashMap<Integer,Integer> maxInd = new HashMap<>();
	    int max = 0;
	    for(int i=0;i<n;i++)
	    {
	        if(maxInd.containsKey(arr[i]))
	        {
	            int j = maxInd.get(arr[i]); // storing previous index of that element
	            max = Math.max(max,i-(maxInd.get(arr[i])));
	            maxInd.put(arr[i],j); // assigning same previous index
	        }
	        else
	        {
	            maxInd.put(arr[i],i);
	        }
	    }
        return max;
    }
}
0
vrajeshmodi991 month ago
 int maxDistance(int arr[], int n){
        unordered_map<int,pair<int,int>>mp;
        for(int i=0;i<n;i++)
        {
            if(mp.count(arr[i])){
                mp[arr[i]].second = i;
            }
            else{
             mp[arr[i]] = make_pair(i,i);   
            }
        }
        int ans=INT_MIN;
       for (auto it: mp){
            auto ele_pair = it.second;
            int diff =ele_pair.second-ele_pair.first;
            ans = max(ans ,diff);
       }
        return ans;
    }
0
aalap02111 month ago
JAVA Solution.Using the map to see if the element is already there. If element is three in the map then calculate the the distance. If distance is more than the current max value, change the max value.
 
class Solution{   int maxDistance(int arr[], int n)   {       Map<Integer,Integer> map = new HashMap<Integer,Integer>();       int maxDistance = 0;       for(int i=0;i<n;i++){           if(map.get(arr[i])==null){               map.put(arr[i],i);           }else{               int mapValue = map.get(arr[i]);               if(maxDistance<(i-mapValue)){                   maxDistance = i-mapValue;               }           }                  }return maxDistance;   }}
-1
abhaybaranwal4
This comment has been flagged for violating our community guidelines.
-1
abhaybaranwal4
This comment has been flagged for violating our community guidelines.
-1
abhaybaranwal4
This comment has been flagged for violating our community guidelines.
-1
abhaybaranwal4
This comment has been flagged for violating our community guidelines.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.