




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.
1using System;
2using System.Collections.Generic;
3
4class DegreeOfArray {
5    public static int FindShortestSubarray(int[] nums) {
6        Dictionary<int, int> count = new Dictionary<int, int>();
7        Dictionary<int, int> first = new Dictionary<int, int>();
8        Dictionary<int, int> last = new Dictionary<int, int>();
9        int degree = 0, minLen = nums.Length;
10
11        for (int i = 0; i < nums.Length; i++) {
12            int num = nums[i];
13            if (!count.ContainsKey(num)) count[num] = 0;
14            count[num]++;
15            if (!first.ContainsKey(num)) first[num] = i;
16            last[num] = i;
17            degree = Math.Max(degree, count[num]);
18        }
19
20        foreach (int num in count.Keys) {
21            if (count[num] == degree) {
22                minLen = Math.Min(minLen, last[num] - first[num] + 1);
23            }
24        }
25        return minLen;
26    }
27
28    static void Main(string[] args) {
29        int[] nums = { 1, 2, 2, 3, 1 };
30        Console.WriteLine(FindShortestSubarray(nums));
31    }
32}In C#, Dictionaries are used to track elements' counts and their first and last indices. The algorithm determines the smallest subarray length with the array's degree by iterating through these mappings.
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
A JavaScript execution leveraging simple plain objects for hash management, enabling efficient consecutive passes to validate the shortest subarrays given collection degree.