Degree of an Array

easy array hash map

Problem

Given a non-empty array of non-negative integers, the degree of the array is the maximum frequency of any element. Find the smallest possible length of a contiguous subarray that has the same degree.

Inputnums = [1, 2, 2, 3, 1]
Output2
Degree is 2 (both 1 and 2). Shortest range with degree 2 is [2, 2] (length 2).

def find_shortest_subarray(nums):
    first, count = {}, {}
    degree, ans = 0, len(nums)
    for i, v in enumerate(nums):
        first.setdefault(v, i)
        count[v] = count.get(v, 0) + 1
        if count[v] > degree:
            degree = count[v]
            ans = i - first[v] + 1
        elif count[v] == degree:
            ans = min(ans, i - first[v] + 1)
    return ans
function findShortestSubArray(nums) {
  const first = new Map(), count = new Map();
  let degree = 0, ans = nums.length;
  for (let i = 0; i < nums.length; i++) {
    const v = nums[i];
    if (!first.has(v)) first.set(v, i);
    count.set(v, (count.get(v) || 0) + 1);
    if (count.get(v) > degree) { degree = count.get(v); ans = i - first.get(v) + 1; }
    else if (count.get(v) === degree) ans = Math.min(ans, i - first.get(v) + 1);
  }
  return ans;
}
class Solution {
    public int findShortestSubArray(int[] nums) {
        Map<Integer, Integer> first = new HashMap<>(), count = new HashMap<>();
        int degree = 0, ans = nums.length;
        for (int i = 0; i < nums.length; i++) {
            int v = nums[i];
            first.putIfAbsent(v, i);
            count.merge(v, 1, Integer::sum);
            if (count.get(v) > degree) { degree = count.get(v); ans = i - first.get(v) + 1; }
            else if (count.get(v) == degree) ans = Math.min(ans, i - first.get(v) + 1);
        }
        return ans;
    }
}
int findShortestSubArray(vector<int>& nums) {
    unordered_map<int, int> first, count;
    int degree = 0, ans = nums.size();
    for (int i = 0; i < (int)nums.size(); i++) {
        int v = nums[i];
        if (!first.count(v)) first[v] = i;
        count[v]++;
        if (count[v] > degree) { degree = count[v]; ans = i - first[v] + 1; }
        else if (count[v] == degree) ans = min(ans, i - first[v] + 1);
    }
    return ans;
}
Time: O(n) Space: O(n)