




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.
1#include <iostream>
2#include <vector>
3#include <unordered_map>
4using namespace std;
5
6int findShortestSubarray(vector<int>& nums) {
7    unordered_map<int, int> count, first, last;
8    int degree = 0, minLen = nums.size();
9    for (int i = 0; i < nums.size(); i++) {
10        int num = nums[i];
11        count[num]++;
12        if (first.find(num) == first.end()) {
13            first[num] = i;
14        }
15        last[num] = i;
16        degree = max(degree, count[num]);
17    }
18    for (const auto& kv : count) {
19        if (kv.second == degree) {
20            minLen = min(minLen, last[kv.first] - first[kv.first] + 1);
21        }
22    }
23    return minLen;
24}
25
26int main() {
27    vector<int> nums = {1, 2, 2, 3, 1};
28    cout << findShortestSubarray(nums) << endl;
29    return 0;
30}This C++ solution mirrors the C solution but utilizes C++'s STL unordered_map to handle frequency and position tracking. First occurrences, last occurrences, and element counting are achieved efficiently.
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.