Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Smallest possible length constituting greatest frequency in JavaScript
This problem asks us to find the smallest contiguous subarray that contains the maximum frequency of any element found in the entire array. We need to track element frequencies and their position ranges to determine the shortest span.
Problem Understanding
Given an array, we must:
- Find the maximum frequency of any element in the entire array
- Identify the shortest contiguous subarray where some element appears with this maximum frequency
- Return the length of this shortest subarray
Example Walkthrough
For the array [55, 77, 77, 88, 55]:
- Element 55 appears twice (positions 0 and 4)
- Element 77 appears twice (positions 1 and 2)
- Element 88 appears once (position 3)
- Maximum frequency is 2
- Shortest subarray with frequency 2:
[77, 77](length 2)
Solution Implementation
const arr = [55, 77, 77, 88, 55];
const shortestLength = (arr) => {
let maxFreq = 0;
let minLen = Infinity;
arr.reduce((acc, num, index) => {
if (acc[num] !== undefined) {
acc[num].freq += 1;
acc[num].range[1] = index;
} else {
acc[num] = {
freq: 1,
range: [index, index]
};
}
// Update max frequency and minimum length
if (acc[num].freq > maxFreq) {
maxFreq = acc[num].freq;
minLen = acc[num].range[1] - acc[num].range[0] + 1;
} else if (acc[num].freq === maxFreq) {
minLen = Math.min(
minLen,
acc[num].range[1] - acc[num].range[0] + 1
);
}
return acc;
}, {});
return minLen;
};
console.log(shortestLength(arr));
2
How It Works
The algorithm uses reduce() to iterate through the array once:
- Tracking: For each element, we store its frequency and position range (first and last occurrence)
- Updating: When we encounter an element again, we increment its frequency and update the end position
- Comparing: We track the maximum frequency seen so far and the minimum length of any subarray achieving that frequency
Test with Different Input
const testArray = [1, 2, 2, 3, 1, 1, 3]; console log(shortestLength(testArray)); // Element frequencies: 1 appears 3 times, 2 appears 2 times, 3 appears 2 times // Max frequency is 3 (element 1) // Shortest subarray containing 3 occurrences of 1: [1, 2, 2, 3, 1, 1] = length 6
6
Key Points
- Time complexity: O(n) - single pass through the array
- Space complexity: O(k) - where k is the number of unique elements
- The solution efficiently tracks both frequency and position ranges in one pass
- It handles ties by keeping the minimum length among subarrays with maximum frequency
Conclusion
This solution efficiently finds the shortest contiguous subarray containing the maximum frequency by tracking element frequencies and position ranges in a single pass. The algorithm ensures optimal performance while handling all edge cases.
Advertisements
