




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.
1using System.Collections.Generic;
class DegreeOfArray {
    public static int FindShortestSubarray(int[] nums) {
        Dictionary<int, int> count = new Dictionary<int, int>();
        Dictionary<int, int> first = new Dictionary<int, int>();
        Dictionary<int, int> last = new Dictionary<int, int>();
        int degree = 0, minLen = nums.Length;
        for (int i = 0; i < nums.Length; i++) {
            int num = nums[i];
            if (!count.ContainsKey(num)) count[num] = 0;
            count[num]++;
            if (!first.ContainsKey(num)) first[num] = i;
            last[num] = i;
            degree = Math.Max(degree, count[num]);
        }
        foreach (int num in count.Keys) {
            if (count[num] == degree) {
                minLen = Math.Min(minLen, last[num] - first[num] + 1);
            }
        }
        return minLen;
    }
    static void Main(string[] args) {
        int[] nums = { 1, 2, 2, 3, 1 };
        Console.WriteLine(FindShortestSubarray(nums));
    }
}A double-scan approach designed in C#, manipulating Dictionary-based measurements of counts and positions to manage efficient discovery of subarrays with the right degree.