JavaScript Program to find Maximum Distance Between two Occurrences of Same Element in Array
Last Updated :
26 Aug, 2024
Given an array of repeated elements, the task is to find the maximum distance between two occurrences of an element.
Example:
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
Brute Force
- Use a dictionary to store element indices.
- Initialize max distance as -1.
- Iterate through the array.
- Update max distance when encountering the same element.
- Return the maximum distance found.
Example: Below are implementations of the idea.
JavaScript
function maxDistance(arr) {
let dict = {};
let maxD = -1;
for (let i = 0; i < arr.length; i++) {
if (dict[arr[i]] !== undefined) {
maxD = Math.max(maxD, i - dict[arr[i]]);
} else {
dict[arr[i]] = i;
}
}
return maxD;
}
let arr = [1, 2, 4, 1, 3, 4, 2, 5, 6, 5];
console.log(
"Max distance between occurrences of same element: "
+ maxDistance(arr));
OutputMax distance between occurrences of same element: 5
Time Complexity: O(N^2)
Space Complexity: O(1)
Optimal Solution
- Use a
Map
to store the first occurrence index of each element. - Iterates through the array, updating the maximum distance for repeated elements.
- Returns the maximum distance found between occurrences of the same element in the array.
Example: Below are implementations of the idea.
JavaScript
function maxDistance(arr, n) {
let map = new Map();
let maxDist = 0;
for (let i = 0; i < n; i++) {
if (!map.has(arr[i]))
map.set(arr[i], i);
else
maxDist = Math.max(maxDist, i - map.get(arr[i]));
}
return maxDist;
}
let arr = [1, 2, 4, 1, 3, 4, 2, 5, 6, 5];
console.log(
"Max distance between occurrences of same element: "
+ maxDistance(arr,10));
OutputMax distance between occurrences of same element: 5
Time Complexity: O(N) under the assumption that unordered_map’s search and insert operations take O(1) time.
Space Complexity: O(N)
Sorting and Two-Pointer Approach
In this method, we first store the indices of each element in a dictionary. Then, we sort the indices of each element and use a two-pointer approach to find the maximum distance for each element.
Example:
Input: arr = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2]
Output: 10
Explanation:
- Maximum distance for
2
is 11 - 1 = 10
- Maximum distance for
1
is 4 - 2 = 2
- Maximum distance for
4
is 10 - 5 = 5
Example:
JavaScript
function maxDistance(arr) {
const elementIndices = {};
// Store indices of each element
for (let i = 0; i < arr.length; i++) {
if (elementIndices[arr[i]] === undefined) {
elementIndices[arr[i]] = [];
}
elementIndices[arr[i]].push(i);
}
let maxDist = -1;
// Iterate through each element in the dictionary
for (const key in elementIndices) {
const indices = elementIndices[key];
if (indices.length > 1) {
// Find the max distance using first and last index
const dist = indices[indices.length - 1] - indices[0];
maxDist = Math.max(maxDist, dist);
}
}
return maxDist;
}
// Examples
const arr1 = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2];
console.log(maxDistance(arr1)); // Output: 10
const arr2 = [1, 1, 1, 1];
console.log(maxDistance(arr2)); // Output: 3
const arr3 = [1, 2, 3, 4, 5];
console.log(maxDistance(arr3)); // Output: -1 (no repeated elements)
Prefix Sum with Hash Map
Idea:
- Use a Hash Map to store the first occurrence index of each element.
- Compute Distances dynamically while iterating through the array.
- Update Maximum Distance if a larger distance is found.
Steps:
- Initialize a Hash Map: This map will store the first occurrence index of each element.
- Iterate Through the Array: For each element:
- If the element is not in the map, store its index as its first occurrence.
- If the element is already in the map, calculate the distance from its first occurrence to the current index.
- Update the maximum distance if the calculated distance is larger.
- Return the Maximum Distance.
Example:
JavaScript
function maxDistance(arr) {
let map = new Map();
let maxDist = -1;
for (let i = 0; i < arr.length; i++) {
if (!map.has(arr[i])) {
map.set(arr[i], i);
} else {
const firstIndex = map.get(arr[i]);
maxDist = Math.max(maxDist, i - firstIndex);
}
}
return maxDist;
}
const arr1 = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2];
console.log(maxDistance(arr1));
const arr2 = [1, 1, 1, 1];
console.log(maxDistance(arr2));
const arr3 = [1, 2, 3, 4, 5];
console.log(maxDistance(arr3));
Similar Reads
JavaScript Program to Find the Distance Value between Two Arrays We will be given two integer arrays and an integer d. The task is to calculate the distance between the two given arrays based on the given integer value. The distance value will be calculated as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <=
3 min read
Javascript Program to Maximize count of corresponding same elements in given Arrays by Rotation Given two arrays arr1[] and arr2[] of N integers and array arr1[] has distinct elements. The task is to find the maximum count of corresponding same elements in the given arrays by performing cyclic left or right shift on array arr1[]. Examples: Input: arr1[] = { 6, 7, 3, 9, 5 }, arr2[] = { 7, 3, 9,
3 min read
Javascript Program to Find closest number in array Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers. Examples: Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9} Target number = 11 Output : 9 9 is closest to 11 in given array Input :arr[] = {2, 5, 6, 7, 8, 8, 9};
4 min read
Finding Maximum Element of Java ArrayList For finding the maximum element in the ArrayList, complete traversal of the ArrayList is required. There is an inbuilt function in the ArrayList class to find the maximum element in the ArrayList, i.e. Time Complexity is O(N), where N is the size of ArrayList, Let's discuss both the methods. Example
2 min read
Find the Minimum Distance Between Two Numbers in PHP Given two numbers A and B, and an array arr containing multiple occurrences of these numbers, the task is to find the minimum distance between the given numbers X and Y. It is guaranteed that the array will contain at least one occurrence of both A and B. Examples: Input:A[] = {1,2,3,2}x = 1, y = 2O
4 min read
How to Find the Maximum Element in an Array? In Java, the array is a data structure that allows the users to store data of the same type in contiguous memory locations. To find the maximum element in an Array in Java, we can sort the array in ascending order using the Arrays.sort() method and then we can access the last element of the array wh
1 min read
Find the most frequent element K positions apart from X in given Array Given an array nums[], and integer K and X, the task is to find the most frequent element K positions away from X in the given array. Examples: Input: nums = [1, 100, 200, 1, 100], K = 1, X = 1Output: 100Explanation: Elements 1 position apart from 1 is only 100.So the answer is 100. Input: nums = [2
6 min read
Javascript Program for Largest Sum Contiguous Subarray Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers that has the largest sum. Kadane's Algorithm:Initialize: max_so_far = INT_MIN max_ending_here = 0Loop for each element of the array (a) max_ending_here = max_ending_here + a[i] (b) if(max_so_f
5 min read
Find Shortest Word Distance II Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array. Implement the WordDistance class: WordDistance(String[] wordsDict): constructor to initialize the object with the strings arr
7 min read
How to Efficiently Remove Duplicates from an Array without using Set? Arrays are a fundamental data structure in Java that stores data of the same type in contiguous memory locations. Removing duplicate elements from an array is a common operation that can be easily accomplished using sets. However, in this article, we will learn how to remove duplicates from an array
2 min read