Open In App

Maximum distance between two occurrences of same element in array

Last Updated : 11 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Below is the implementations of the idea.

C++




// C++ program to find the maximum distance between
// two equal elements
#include <bits/stdc++.h>
  
// 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));
    }
}


Python3




def max_distance(arr):
    n = len(arr)
    max_d = -1
    for i in range(n - 1):
        for j in range(i + 1, n):
            if arr[i] == arr[j]:
                temp = abs(j - i)
                max_d = max(max_d, temp)
    return max_d
  
# Driver code
arr = [1, 2, 4, 1, 3, 4, 2, 5, 6, 5]
print("Maximum distance between two occurrences of same element in array:", max_distance(arr))


C#




using System;
  
class MainClass {
    // 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 };
        Console.WriteLine(
            "Maximum distance between two occurrences of same element in array: {0}",
            maxDistance(Arr, 10));
    }
}


Javascript




// JavaScript program to find the maximum distance between
// two equal elements in an array
  
// function to find the maximum distance
function maxDistance(arr) { 
// create a dictionary to store element indices
let dict = {};
  
// initialize the maxD to -1
let maxD = -1;
  
// loop through the array
for (let i = 0; i < arr.length; i++) {
    // check if the element is already present in the dictionary
    if (dict[arr[i]] !== undefined) {
        // calculate the distance and update maxD
        let temp = i - dict[arr[i]];
        maxD = maxD > temp ? maxD : temp;
    } else {
        // if the element is not present in the dictionary, add it
        dict[arr[i]] = i;
    }
}
  
// return maximum distance
return maxD;
}
  
// Driver code
let Arr = [1, 2, 4, 1, 3, 4, 2, 5, 6, 5];
console.log("Maximum distance between two occurrences of same element in array: " + maxDistance(Arr));


Output

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

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

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<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;
}


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


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




<script>
  
// Javascript program to find maximum distance between two 
// same occurrences of a number.
  
    // Function to find maximum distance between equal elements 
    function maxDistance(arr, n)
    {
        // Used to store element to first index mapping
        let map = new Map();
            
        // Traverse elements and find maximum distance between 
        // same occurrences with the help of map. 
        let max_dist = 0;
    
        for (let i = 0; i < n; i++)
        {
            // If this is first occurrence of element, insert its 
            // index in map 
            if (!map.has(arr[i]))
                map.set(arr[i], i);
    
            // Else update max distance 
            else
                max_dist = Math.max(max_dist, i - map.get(arr[i]));
        }
    
        return max_dist;
}
  
// Driver program 
  
    let arr = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2];
    let n = arr.length;
    document.write(maxDistance(arr, n));
  
</script>


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).

 



Previous Article
Next Article

Similar Reads

Minimum distance between two occurrences of maximum
You are given an array of n-elements with a basic condition that occurrence of greatest element is more than once. You have to find the minimum distance between maximums. (n&gt;=2). Examples: Input : arr[] = {3, 5, 2, 3, 5, 3, 5} Output : Minimum Distance = 2 Explanation : Greatest element is 5 and its index are 1, 4 and 6. Resulting minimum distan
5 min read
Maximise distance by rearranging all duplicates at same distance in given Array
Given an array arr[] of N integers. Arrange the array in a way such that the minimum distance among all pairs of same elements is maximum among all possible arrangements. The task is to find this maximum value. Examples: Input: arr[] = {1, 1, 2, 3}Output: 3Explanation: All possible arrangements are: {1, 1, 2, 3}, {1, 1, 3, 2}, {1, 2, 1, 3}, {1, 2,
6 min read
Rearrange Linked List to make XOR of nodes at same distance from start and end same
Given a linked list containing N nodes of binary numbers, the task is to check whether it is possible to rearrange the linked list in such a way that value of XOR between element at ith Node and N+1−ith node is the same for all 1 ≤ i ≤ N. Print Yes, if the Linked List can be rearranged, or else print No. Examples: Input: LL = 0 -&gt; 0 -&gt; 1Outpu
8 min read
Remove all continuous occurrences of 'a' and all occurrences of 'b'
Given a string str, the task is to remove all the continuous occurrences of a and all occurrences of b and print the resultant string. Examples Input: str = "abcddabcddddabbbaaaaaa" Output: acddacdddda 'abcddabcddddabbbaaaaaa' will not result in 'acddacddddaa' because after removing the required occurrences, the string will become 'acddacddddaa' wh
10 min read
Count pairs of same parity indexed elements with same MSD after replacing each element by the sum of maximum digit * A and minimum digits * B
Given an array arr[] of N 3-digit integers and two integers a and b, the task is to modify each array element according to the following rules: Find the maximum, say M, and minimum digit, say m, of each array element arr[i].Update the array element arr[i] as (A * M + B * m). The task is to count the number of pairs such that the chosen elements are
12 min read
Generate array having differences between count of occurrences of every array element on its left and right
Given an array A[] consisting of N integers, the task is to construct an array B[] such that for every ith index, B[i] = X - Y, where X and Y are the count of occurrences of A[i] after and before the ith index. Examples: Input: A[] = {3, 2, 1, 2, 3}Output: 1 1 0 -1 -1Explanation: arr[0] = 3, X = 1, Y = 0. Therefore, print 1. arr[1] = 2, X = 1, Y =
6 min read
Bitwise XOR of same indexed array elements after rearranging an array to make XOR of same indexed elements of two arrays equal
Given two arrays A[] and B[] consisting of N positive integers, the task is to the Bitwise XOR of same indexed array elements after rearranging the array B[] such that the Bitwise XOR of the same indexed elements of the arrays A[] becomes equal. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 6, 7}Output: 5Explanation:Below are the possible arrangement
14 min read
Minimum distance between the maximum and minimum element of a given Array
Given an array A[] consisting of N elements, the task is to find the minimum distance between the minimum and the maximum element of the array.Examples: Input: arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2} Output: 3 Explanation: The minimum element(= 1) is present at indices {2, 4} The maximum element(= 8) is present at indices {7, 10}. The minimum
8 min read
Remove all occurrences of any element for maximum array sum
Given an array of positive integers, remove all the occurrences of the element to get the maximum sum of the remaining array. Examples: Input : arr = {1, 1, 3} Output : 3 On removing 1 from the array, we get {3}. The total value is 3 Input : arr = {1, 1, 3, 3, 2, 2, 1, 1, 1} Output : 11 On removing 2 from the array, we get {1, 1, 3, 3, 1, 1, 1}. Th
6 min read
Queries to count occurrences of maximum array element in subarrays starting from given indices
Given two arrays arr[] and q[] consisting of N integers, the task is for each query q[i] is to determine the number of times the maximum array element occurs in the subarray [q[i], arr[N - 1]]. Examples: Input: arr[] = {5, 4, 5, 3, 2}, q[] = {1, 2, 3, 4, 5}Output: 2 1 1 1 1Explanation:For the first query index start from 1. The subarray is [5, 4, 5
11 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg