> For the complete documentation index, see [llms.txt](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/array/697.-degree-of-an-array.md).

# 697. Degree of an Array

Given a non-empty array of non-negative integers `nums`, the **degree** of this array is defined as the maximum frequency of any one of its elements.

Your task is to find the smallest possible length of a (contiguous) subarray of `nums`, that has the same degree as `nums`.

**Example 1:**<br>

```
Input: [1, 2, 2, 3, 1]
Output: 2
Explanation: 
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.
```

**Example 2:**<br>

```
Input: [1,2,2,3,1,4,2]
Output: 6
```

**Note:**

`nums.length` will be between 1 and 50,000.

`nums[i]` will be an integer between 0 and 49,999.

{% hint style="info" %}
用兩個hashmap分別紀錄每個數字對應到的次數還有第一次出現的位置。
{% endhint %}

```cpp
// One Pass with Two Hashmaps
int findShortestSubArray(vector<int>& nums) { // time: O(n); space: O(n)
    unordered_map<int, int> counter, first;
    int degree = 0, len = INT_MAX;
    for (int i = 0; i < (int)nums.size(); ++i) {
        if (!first.count(nums[i])) first[nums[i]] = i;
        if (++counter[nums[i]] > degree) {
            degree = counter[nums[i]];
            len = i - first[nums[i]] + 1;
        } else if (counter[nums[i]] == degree) {
            len = min(len, i - first[nums[i]] + 1);
        }
    }
    return len;
}
```

{% hint style="info" %}
也可以把出現次數和出現位置合併在一個hashmap的value裡，這邊value用vector\<int>表示，vector size為3，紀錄{出現次數, 第一次出現位置, 最後一次出現位置}。第一個for loop完可以建構出這個hashmap，第二次loop整個hashmap中的所有entry，然後根據value的vector來判斷。
{% endhint %}

```cpp
// Two Pass with One Hashmap
int findShortestSubArray(vector<int>& nums) { // time: O(n); space: O(n)
    unordered_map<int, vector<int> > mp; // num in the array -> <times, first idx, last idx>
    for (int i = 0; i < (int)nums.size(); ++i) {
        if (!mp.count(nums[i])) {
            mp[nums[i]] = {1, i, i};
        } else {
            ++mp[nums[i]][0];
            mp[nums[i]][2] = i;
        }
    }
    int degree = INT_MIN, res = INT_MAX;
    for (auto& e : mp) {
        vector<int> v = e.second;
        if (v[0] > degree) {
            degree = v[0];
            res = v[2] - v[1] + 1;
        } else if (v[0] == degree) {
            res = min(res, v[2] - v[1] + 1);
        }
    }
    return res;
}
```
