




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.
1def findShortestSubarray(nums):
2    from collections import defaultdict
3    count = defaultdict(int)
4    first, last = {}, {}
5    degree, minLen = 0, len(nums)
6    
7    for i, num in enumerate(nums):
8        count[num] += 1
9        if num not in first:
10            first[num] = i
11        last[num] = i
12        degree = max(degree, count[num])
13    
14    for num in count:
15        if count[num] == degree:
16            minLen = min(minLen, last[num] - first[num] + 1)
17    
18    return minLen
19
20if __name__ == "__main__":
21    nums = [1, 2, 2, 3, 1]
22    print(findShortestSubarray(nums))This Python solution uses collections' defaultdict to manage count tracking and maintains dictionaries for the first and last positions. It efficiently determines the shortest subarray with the array's degree.
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.