Skip to content

Commit df80bb4

Browse files
authored
Create degree-of-an-array.py
1 parent 1e8a763 commit df80bb4

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Python/degree-of-an-array.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
# Given a non-empty array of non-negative integers nums,
5+
# the degree of this array is defined as the maximum frequency of any one of its elements.
6+
#
7+
# Your task is to find the smallest possible length of a (contiguous) subarray of nums,
8+
# that has the same degree as nums.
9+
#
10+
# Example 1:
11+
# Input: [1, 2, 2, 3, 1]
12+
# Output: 2
13+
# Explanation:
14+
# The input array has a degree of 2 because both elements 1 and 2 appear twice.
15+
# Of the subarrays that have the same degree:
16+
# [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
17+
# The shortest length is 2. So return 2.
18+
#
19+
# Example 2:
20+
# Input: [1,2,2,3,1,4,2]
21+
# Output: 6
22+
# Note:
23+
#
24+
# nums.length will be between 1 and 50,000.
25+
# nums[i] will be an integer between 0 and 49,999.
26+
27+
class Solution(object):
28+
def findShortestSubArray(self, nums):
29+
"""
30+
:type nums: List[int]
31+
:rtype: int
32+
"""
33+
counts = collections.Counter(nums)
34+
left, right = {}, {}
35+
for i, num in enumerate(nums):
36+
left.setdefault(num, i)
37+
right[num] = i
38+
degree = max(counts.values())
39+
return min(right[num]-left[num]+1 \
40+
for num in counts.keys() \
41+
if counts[num] == degree)
42+

0 commit comments

Comments
 (0)