Max Distance Between Two Occurrences
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 = 5Input: arr[] = [1, 2, 3, 6, 5, 4]
Output: 0
Explanation: No element has two occurrence, so maximum distance = 0.
Table of Content
[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.
// C++ Program to find max distance between two occurrences
// in array by exploring all pairs
#include <iostream>
#include <vector>
using namespace std;
// function to find the maximum distance
int maxDistance(vector<int>& arr) {
int res = 0;
for (int i = 0; i < arr.size() - 1; i++) {
for (int j = i + 1; j < arr.size(); j++) {
// check if two elements are equal
if (arr[i] == arr[j]) {
// calculate the distance and update res
res = max(res, j - i);
}
}
}
return res;
}
// Driver code
int main() {
vector<int> arr = {1, 2, 4, 1, 3, 4, 2, 5, 6, 5};
cout << maxDistance(arr) << endl;
return 0;
}
// C Program to find max distance between two occurrences
// in array by exploring all pairs
#include <stdio.h>
#include <stdlib.h>
// function to find the maximum distance
int maxDistance(int arr[], int n) {
int res = 0;
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]) {
// calculate the distance and update res
res = (res > (j - i)) ? res : (j - i);
}
}
}
return res;
}
int main() {
int arr[] = {1, 2, 4, 1, 3, 4, 2, 5, 6, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", maxDistance(arr, n));
return 0;
}
// Java Program to find max distance between two occurrences
// in array by exploring all pairs
import java.util.Arrays;
class GfG {
// function to find the maximum distance
static int maxDistance(int[] arr) {
int res = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
// check if two elements are equal
if (arr[i] == arr[j]) {
// calculate the distance and update res
res = Math.max(res, j - i);
}
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {1, 2, 4, 1, 3, 4, 2, 5, 6, 5};
System.out.println(maxDistance(arr));
}
}
# Python Program to find max distance between two occurrences
# in array by exploring all pairs
def maxDistance(arr):
res = 0
for i in range(len(arr) - 1):
for j in range(i + 1, len(arr)):
# check if two elements are equal
if arr[i] == arr[j]:
# calculate the distance and update res
res = max(res, j - i)
return res
if __name__ == "__main__":
arr = [1, 2, 4, 1, 3, 4, 2, 5, 6, 5]
print(maxDistance(arr))
// C# Program to find max distance between two occurrences
// in array by exploring all pairs
using System;
class GfG {
// function to find the maximum distance
static int maxDistance(int[] arr) {
int res = 0;
for (int i = 0; i < arr.Length - 1; i++) {
for (int j = i + 1; j < arr.Length; j++) {
// check if two elements are equal
if (arr[i] == arr[j]) {
// calculate the distance and update res
res = Math.Max(res, j - i);
}
}
}
return res;
}
static void Main() {
int[] arr = new int[]{1, 2, 4, 1, 3, 4, 2, 5, 6, 5};
Console.WriteLine(maxDistance(arr));
}
}
// JavaScript Program to find max distance between two occurrences
// in array by exploring all pairs
// function to find the maximum distance
function maxDistance(arr) {
let res = 0;
for (let i = 0; i < arr.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
// check if two elements are equal
if (arr[i] === arr[j]) {
// calculate the distance and update res
res = Math.max(res, j - i);
}
}
}
return res;
}
// Driver code
const arr = [1, 2, 4, 1, 3, 4, 2, 5, 6, 5];
console.log(maxDistance(arr));
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.
// C++ Program to find max distance between two occurrences
// in array using hashing
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int maxDistance(vector<int>& arr) {
// Stores element to first index mapping
unordered_map<int, int> mp;
int res = 0;
for (int i = 0; i < arr.size(); i++) {
// If this is the first occurrence of
// the element, store its index
if (mp.find(arr[i]) == mp.end())
mp[arr[i]] = i;
// Else update max distance
else
res = max(res, i - mp[arr[i]]);
}
return res;
}
int main() {
vector<int> arr = {1, 1, 2, 2, 2, 1};
cout << maxDistance(arr);
return 0;
}
// Java Program to find max distance between two occurrences
// in array using hashing
import java.util.*;
class GfG {
static int maxDistance(int[] arr) {
// Stores element to first index mapping
HashMap<Integer, Integer> mp = new HashMap<>();
int res = 0;
for (int i = 0; i < arr.length; i++) {
// If this is the first occurrence of the
// element, store its index
if (!mp.containsKey(arr[i]))
mp.put(arr[i], i);
// Else update max distance
else
res = Math.max(res, i - mp.get(arr[i]));
}
return res;
}
public static void main(String[] args) {
int[] arr = {1, 1, 2, 2, 2, 1};
System.out.println(maxDistance(arr));
}
}
# Python Program to find max distance between two occurrences
# in array using hashing
def maxDistance(arr):
# Stores element to first index mapping
mp = {}
res = 0
for i in range(len(arr)):
# If this is the first occurrence of the
# element, store its index
if arr[i] not in mp:
mp[arr[i]] = i
# Else update max distance
else:
res = max(res, i - mp[arr[i]])
return res
if __name__ == "__main__":
arr = [1, 1, 2, 2, 2, 1]
print(maxDistance(arr))
// C# Program to find max distance between two occurrences
// in array using hashing
using System;
using System.Collections.Generic;
class GfG {
static int maxDistance(int[] arr) {
// Stores element to first index mapping
Dictionary<int, int> mp = new Dictionary<int, int>();
int res = 0;
for (int i = 0; i < arr.Length; i++) {
// If this is the first occurrence of the
// element, store its index
if (!mp.ContainsKey(arr[i])) {
mp[arr[i]] = i;
} else {
// Else update max distance
res = Math.Max(res, i - mp[arr[i]]);
}
}
return res;
}
static void Main() {
int[] arr = {1, 1, 2, 2, 2, 1};
Console.WriteLine(maxDistance(arr));
}
}
// JavaScript Program to find max distance between two
// occurrences in array using hashing
function maxDistance(arr) {
// Stores element to first index mapping
const mp = {};
let res = 0;
for (let i = 0; i < arr.length; i++) {
// If this is the first occurrence of the
// element, store its index
if (!(arr[i] in mp)) {
mp[arr[i]] = i;
} else {
// Else update max distance
res = Math.max(res, i - mp[arr[i]]);
}
}
return res;
}
// Driver Code
const arr = [1, 1, 2, 2, 2, 1];
console.log(maxDistance(arr));
Output
5