Degree of an Array — LeetCode 697 Python Solution

EasyArrayHash Table
Problem
#697
Pattern
Hash Map
Reading time
3 min

The problem

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

Input
nums = [1,2,2,3,1]
Output
2
Explanation
The input array has a degree of 2 because both elements 1 and 2 appear twice.

Python solution

Python
class Solution:
    def findShortestSubArray(self, nums: List[int]) -> int:
        cnt = Counter(nums)
        degree = cnt.most_common()[0][1]
        left, right = {}, {}
        for i, v in enumerate(nums):
            if v not in left:
                left[v] = i
            right[v] = i
        ans = inf
        for v in nums:
            if cnt[v] == degree:
                t = right[v] - left[v] + 1
                if ans > t:
                    ans = t
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 697. Degree of an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 697. Degree of an Array?
LeetCode 697. Degree of an Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 697. Degree of an Array?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 697. Degree of an Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 697. Degree of an Array cover?
LeetCode 697. Degree of an Array is tagged Array and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview