Skip to content
LC-0697 Easy LeetCode

697. Degree of an Array

Read the full problem statement on LeetCode.
Difficulty: easy Acceptance: 57% Topics: Array, Hash Table
View full problem on LeetCode

Reading material

Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(n)

import collections


class Solution(object):
    def findShortestSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        counts = collections.Counter(nums)
        left, right = {}, {}
        for i, num in enumerate(nums):
            left.setdefault(num, i)
            right[num] = i
        degree = max(counts.values())
        return min(right[num]-left[num]+1 \
                   for num in counts.keys() \
                   if counts[num] == degree)

Solution from kamyu104/LeetCode-Solutions · MIT

Similar questions