Degree of an Array

Easy Hash Maps

Problem

Given a non-empty array of non-negative integers nums, return the length of the shortest contiguous subarray of nums that has the same degree as nums.

  • 1 ≤ nums.length ≤ 5 * 10⁴
  • 0 ≤ nums[i] ≤ 10⁵

Example

Input: nums = [1, 2, 2, 3, 1]
Output: 2

The degree of the array is 2 because both elements 1 and 2 appear twice. The shortest subarray with degree 2 for element 1 is [1, 2, 2, 3, 1] (length 5), but for element 2 it is [2, 2] (length 2). The algorithm tracks the first and last occurrence of each number and their counts. It finds the degree as 2 and then iterates over all numbers with this degree to find the minimal subarray length, which is 2 for number 2.

Approach

Straightforward Solution

A brute-force approach would check every subarray and count frequencies, resulting in O(n^2) or worse time complexity, which is infeasible for large inputs.

Core Observation

The degree of the array is the highest frequency of any element. To find the shortest subarray with the same degree, one must consider the elements that achieve this maximum frequency and find the minimal distance between their first and last occurrences.

Path to Optimal

The key insight is to track three pieces of information for each unique element: its frequency count, its first occurrence index, and its last occurrence index. This allows computing the degree in a single pass and then determining the minimal subarray length for elements with that degree in a second pass, achieving O(n) time complexity.

Optimal Approach

Use three hash maps to track counts, first indices, and last indices of each element while iterating once through the array. Then find the maximum frequency (degree) and iterate over elements with that frequency to find the minimal subarray length defined by last_index - first_index + 1.

Time

O(n)

The solution iterates through the array once to build frequency and index maps, then iterates over the unique keys once to find the minimal subarray length, resulting in linear time complexity.

Space

O(n)

Three hash maps store counts and indices for each unique element, which in the worst case can be all elements, leading to O(n) auxiliary space.

Pattern Spotlight

Hash Maps (Frequency Counting with Index Tracking)

When a problem requires frequency-based properties combined with positional constraints, maintain hash maps for counts and first/last occurrences to enable O(1) lookups and a single-pass solution.

Solution

1class Solution:
2 def findShortestSubArray(self, nums: list[int]) -> int:
3 counts = {}
4 first_index = {}
5 last_index = {}
6
7 for index, num in enumerate(nums):
8 counts[num] = counts.get(num, 0) + 1
9
10 if num not in first_index:
11 first_index[num] = index
12
13 last_index[num] = index
14
15 degree = max(counts.values())
16 min_length = len(nums)
17
18 for num in counts:
19 if counts[num] == degree:
20 current_length = last_index[num] - first_index[num] + 1
21 min_length = min(min_length, current_length)
22
23 return min_length

Step-by-Step Solution

1

Accumulate Frequency and Track First and Last Occurrences

3counts = {}
4first_index = {}
5last_index = {}
7for index, num in enumerate(nums):
8 counts[num] = counts.get(num, 0) + 1
10 if num not in first_index:
11 first_index[num] = index
13 last_index[num] = index

Objective

To build frequency counts and record the first and last indices of each element in a single pass.

Key Insight

By simultaneously updating counts and recording the first and last positions of each element, the algorithm captures all necessary information to determine the degree and the boundaries of candidate subarrays without additional passes or complex data structures.

Interview Quick-Check

Core Logic

Maintain three hash maps: one for counts, one for first occurrence indices, and one for last occurrence indices, updating them as the array is traversed.

State & Boundaries

Only set the first occurrence index when the element is seen for the first time to preserve the earliest position.

Common Pitfalls & Bugs

Failing to update the last occurrence index on every encounter would lead to incorrect subarray length calculations.

2

Determine Degree and Initialize Minimal Subarray Length

15degree = max(counts.values())
16min_length = len(nums)

Objective

To find the maximum frequency (degree) of the array and set an initial minimal subarray length for comparison.

Key Insight

The degree is the maximum value in the counts map. Initializing the minimal length to the full array length ensures any valid subarray found will be shorter or equal, enabling correct minimization.

Interview Quick-Check

Core Logic

Compute the degree by taking the maximum frequency from the counts map and initialize the minimal subarray length to the array's length.

Common Pitfalls & Bugs

Not initializing the minimal length to the array length can cause incorrect results if the shortest subarray equals the entire array.

3

Find the Shortest Subarray Matching the Degree

18for num in counts:
19 if counts[num] == degree:
20 current_length = last_index[num] - first_index[num] + 1
21 min_length = min(min_length, current_length)

Objective

To iterate over elements with frequency equal to the degree and update the minimal subarray length based on their first and last occurrence indices.

Key Insight

Only elements that achieve the degree can define candidate subarrays. Calculating the length as last_index - first_index + 1 for these elements and taking the minimum yields the shortest subarray with the same degree.

Interview Quick-Check

Core Logic

For each element with frequency equal to the degree, compute the subarray length from first to last occurrence and update the minimal length accordingly.

State & Boundaries

Iterate over all keys in counts to ensure all candidates are considered.

Common Pitfalls & Bugs

Ignoring elements with frequency less than the degree can lead to incorrect minimal length calculations.

4

Return the Length of the Shortest Subarray with the Same Degree

23return min_length

Objective

To return the minimal subarray length found that matches the array's degree.

Key Insight

After evaluating all candidates, the minimal length variable holds the shortest contiguous subarray length that preserves the degree, which is the problem's required output.

Interview Quick-Check

Core Logic

Return the minimal length computed after considering all elements with maximum frequency.

Line Analysis

This solution has 7 Critical lines interviewers watch for.

Line 15 Critical
degree = max(counts.values())

Determine the degree of the array as the maximum frequency.

The degree defines the frequency threshold for candidate subarrays and is central to the problem's requirement.

Line 8 Critical
counts[num] = counts.get(num, 0) + 1

Increment the frequency count for the current element.

Updating counts on each occurrence builds the frequency distribution needed to find the degree.

Line 11 Critical
first_index[num] = index

Record the first occurrence index for the current element.

Setting this index only on the first encounter captures the left boundary of the element's subarray.

Line 13 Critical
last_index[num] = index

Update the last occurrence index for the current element.

Always updating the last index ensures the right boundary of the element's subarray is accurate.

Line 19 Critical
if counts[num] == degree:

Check if the current element's frequency equals the degree.

Only elements with frequency equal to the degree can define subarrays that preserve the array's degree.

Line 20 Critical
current_length = last_index[num] - first_index[num] + 1

Calculate the length of the subarray spanning the element's first to last occurrence.

This length represents the minimal contiguous subarray containing all occurrences of the element, critical for comparison.

Line 21 Critical
min_length = min(min_length, current_length)

Update the minimal subarray length if the current one is shorter.

Maintaining the minimum ensures the final result is the shortest subarray with the same degree.

Line 3 Core
counts = {}

Initialize a hash map to count frequencies of elements.

This map is essential for tracking how many times each element appears, which defines the array's degree.

Line 4 Core
first_index = {}

Initialize a hash map to record the first occurrence index of each element.

Storing the first index allows calculation of subarray boundaries later, critical for determining minimal subarray length.

Line 5 Core
last_index = {}

Initialize a hash map to record the last occurrence index of each element.

Tracking the last index is necessary to compute the full span of each element's occurrences.

Line 23 Core
return min_length

Return the shortest subarray length found.

This line outputs the final answer after all candidates have been evaluated.

Line 10 Core
if num not in first_index:

Check if the current element has not been seen before.

This condition ensures the first occurrence index is set only once, preserving the earliest position.

Line 16 Core
min_length = len(nums)

Initialize the minimal subarray length to the full array length.

Starting with the maximum possible length ensures any valid subarray found will update this value correctly.

Line 18 Standard
for num in counts:

Iterate over all unique elements in the counts map.

Examining each element is necessary to identify those that match the degree and evaluate their subarray lengths.

Line 7 Standard
for index, num in enumerate(nums):

Iterate over the array with index and element.

Enumerating both index and value is required to update counts and track positions simultaneously.

Test Your Understanding

Why is it necessary to track both the first and last occurrence indices of elements when computing the shortest subarray with the same degree?

Because the shortest subarray containing all occurrences of an element with maximum frequency spans from its first to last occurrence; tracking these indices allows computing the minimal length subarray that preserves the element's full frequency.

Related Problems

Hash Maps pattern

Don't just read it. Drill it.

Reconstruct Degree of an Array from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the Degree of an Array drill

or drill a free problem