




Sponsored
Sponsored
This approach involves creating a HashMap for tracking the frequency of each element, and two other HashMaps to keep track of the first and last indices of each element. The goal is to determine the degree of the array, then find the shortest subarray that has this same degree.
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(n), due to the usage of the arrays to track counts and positions.
1function findShortestSubarray(nums) {
2    let count = {}, first = {}, last = {};
3    let degree = 0, minLen = nums.length;
4
5    nums.forEach((num, i) => {
6        if (!count[num]) count[num] = 0;
7        count[num]++;
8        if (first[num] === undefined) first[num] = i;
9        last[num] = i;
10        degree = Math.max(degree, count[num]);
11    });
12
13    for (let num in count) {
14        if (count[num] === degree) {
15            minLen = Math.min(minLen, last[num] - first[num] + 1);
16        }
17    }
18
19    return minLen;
20}
21
22console.log(findShortestSubarray([1, 2, 2, 3, 1]));In JavaScript, we use objects as hashmaps to record counts, first positions, and last positions. This provides an efficient method to determine the shortest subarray meeting the degree condition.
This approach first calculates the degree of the array in a single pass, then performs a second traversal to identify the smallest contiguous subarray with the same degree. The second traversal uses the frequency and position data collected during the first pass.
Time Complexity: O(n), needing two passes over n elements.
Space Complexity: O(n), primarily due to the need to store index locations.
1
This C implementation involves keeping separate indices arrays for the first and last index occurrences of elements in a straightforward fashion. It performs a thorough scan and uses array indices to track positions.