-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathdegree_of_an_array.py
25 lines (21 loc) · 945 Bytes
/
degree_of_an_array.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from collections import Counter
from typing import List, Dict
class Solution:
def getLeftPosition(self, array: List[int]) -> Dict[int, int]:
positions = {}
for index, element in enumerate(array):
if element not in positions:
positions[element] = index
return positions
def getRightPosition(self, array: List[int]) -> Dict[int, int]:
return {number : index for index, number in enumerate(array)}
def findShortestSubArray(self, numbers: List[int]) -> int:
frequencies = Counter(numbers)
leftMost = self.getLeftPosition(numbers)
rightMost = self.getRightPosition(numbers)
maxFrequency = max(frequencies.values())
result = float('inf')
for number, frequency in frequencies.items():
if frequency == maxFrequency:
result = min(result, rightMost[number] - leftMost[number] + 1)
return result