#697
Degree of an Array
EasyArrayHash TableHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a single pass to count frequencies and track the first and last positions of each element. This allows us to efficiently determine the minimum length of the subarray with the same degree.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each element and track their first and last occurrence indices.
- 2Step 2: Determine the degree of the array from the frequency count.
- 3Step 3: For each element that contributes to the degree, calculate the length of the subarray from its first to last occurrence and update the minimum length.
solution.py18 lines
1# Full working Python code
2from collections import defaultdict
3
4def findShortestSubarray(nums):
5 count = defaultdict(int)
6 first = {}
7 last = {}
8 for i, num in enumerate(nums):
9 count[num] += 1
10 if num not in first:
11 first[num] = i
12 last[num] = i
13 degree = max(count.values())
14 min_length = float('inf')
15 for num in count:
16 if count[num] == degree:
17 min_length = min(min_length, last[num] - first[num] + 1)
18 return min_lengthℹ
Complexity note: This complexity is linear because we traverse the array a constant number of times, resulting in a single pass for counting and another for determining the minimum length.
- 1The degree of an array is determined by the maximum frequency of its elements.
- 2To find the smallest subarray with the same degree, track first and last occurrences of elements.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.