Problem statement

https://leetcode.com/problems/degree-of-an-array/

Solution

For each element find its first and last occurrences. Then use counter to count each frequency, find its maximum and then return minimum among all last[v] - first[v] + 1 for every number with maximum frequency.

Complexity

Time and space complexity is O(n).

Code

class Solution:
    def findShortestSubArray(self, nums):
        last = {v: i for i, v in enumerate(nums)}
        first = {v: len(nums)-i-1 for i, v in enumerate(nums[::-1])}
        c = Counter(nums)
        degree = max(c.values())
        return min(last[v] - first[v] + 1 for v in c if c[v] == degree)