Taro Logo

Degree of an Array

#1 Most AskedEasy
0 views
Topics:
Arrays

Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.

Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.

Example 1:

Input: nums = [1,2,2,3,1]
Output: 2
Explanation: 
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.

Example 2:

Input: nums = [1,2,2,3,1,4,2]
Output: 6
Explanation: 
The degree is 3 because the element 2 is repeated 3 times.
So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.

Constraints:

  • nums.length will be between 1 and 50,000.
  • nums[i] will be an integer between 0 and 49,999.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected range of values for the elements inside the `nums` array, and can they include negative numbers or zeros?
  2. What are the constraints on the size of the input array `nums` (i.e., minimum and maximum length)?
  3. If there are multiple contiguous subarrays of the same minimum length that share the degree of the array, does it matter which one's length we return, or should we consider any specific tie-breaking criteria?
  4. Is the input array guaranteed to be non-empty as stated in the description, or should I explicitly handle empty array inputs?
  5. When we talk about a 'contiguous subarray,' does a subarray of length 1 count as a valid contiguous subarray if the array's degree is 1?

Brute Force Solution

Approach

To solve this problem using the brute force approach, we look at every single possible sub-group of items from the start to the end. For each sub-group, we count how often each item appears to figure out the maximum frequency, and then we find the shortest sub-group that shares that same maximum frequency.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first item and consider every possible ending point to form different sub-groups starting from the beginning.
  2. Move to the second item and do the same thing, forming all possible sub-groups that start there, and continue this process until you have considered every single possible sub-group of items.
  3. For every single sub-group you look at, count how many times each item appears inside it.
  4. Determine the highest count for each sub-group, which represents its degree.
  5. Check which sub-groups have a degree equal to the overall degree of the entire collection of items.
  6. Among those matching sub-groups, measure their lengths by counting how many items are inside them.
  7. Compare the lengths of all the qualifying sub-groups and select the shortest one as your final answer.

Code Implementation

def find_shortest_sub_array(nums):    # Find the overall degree by counting the maximum frequency of any element in the entire array    overall_degree = max([nums.count(item) for item in nums]) if nums else 0    shortest_length = len(nums)    # Generate every possible sub-array to examine their frequencies and lengths    for start_index in range(len(nums)):        for end_index in range(start_index, len(nums)):            sub_array = nums[start_index:end_index + 1]            sub_array_degree = max([sub_array.count(item) for item in sub_array]) if sub_array else 0            # Only consider sub-arrays that match the overall degree to find the minimum length            if sub_array_degree == overall_degree:                current_length = (end_index - start_index) + 1                if current_length < shortest_length:                    shortest_length = current_length    return shortest_length

Big(O) Analysis

Time Complexity
O(n³) – To evaluate every possible sub-group, we use two nested loops to define all possible starting and ending points, which generates roughly n squared sub-groups. Then, for each of those sub-groups, a third inner operation iterates through its elements to count frequencies and determine the degree. Since we process up to n elements for each of the roughly n squared sub-groups, the total operations scale roughly like n cubed over 2, which simplifies to the final Big O time complexity of O(n³).
Space Complexity
O(1) – The brute force approach as described evaluates every possible sub-group, counts item frequencies, and tracks lengths using only a few primitive integer variables for loop indices and maximum counts. Because these variables require a constant amount of extra memory regardless of the input size, the auxiliary space remains fixed. Therefore, the space complexity simplifies to Big O of 1.

Optimal Solution

Approach

To solve this problem efficiently, we need to track how often each item appears and find the shortest stretch between the first and last appearance of the items that appear the most. By keeping notes as we scan through the items just once, we can quickly figure out which items tie for the most frequent and measure their span.

Here's how the algorithm would work step-by-step:

  1. Scan through the entire collection of items from beginning to end while keeping a count of how many times each item shows up.
  2. As you count, remember the exact spot where each item makes its very first appearance so you know where its potential span starts.
  3. Keep updating your notes with the spot where you last saw each item so you always know its most recent location.
  4. Keep track of the highest frequency you encounter, which represents the maximum number of times any single item appears in the collection.
  5. Look through all the items that matched this highest frequency and calculate the distance between their first and last appearances by subtracting the starting spot from the ending spot and adding one.
  6. Compare the distances of all the most frequent items and find the smallest number, which represents the shortest possible section containing a matching degree.

Code Implementation

def find_shortest_sub_array(input_numbers):
    first_seen_positions = {}
    last_seen_positions = {}
    frequency_counts = {}

    # We scan once to record frequencies and boundaries for every item.
    for current_index, current_number in enumerate(input_numbers):
        if current_number not in first_seen_positions:
            first_seen_positions[current_number] = current_index
        last_seen_positions[current_number] = current_index
        frequency_counts[current_number] = frequency_counts.get(current_number, 0) + 1

    maximum_degree = max(frequency_counts.values())
    shortest_span_length = len(input_numbers)

    # We evaluate only the items that share the maximum degree to find the minimum span.
    for current_number, frequency_count in frequency_counts.items():
        if frequency_count == maximum_degree:
            current_span_length = last_seen_positions[current_number] - first_seen_positions[current_number] + 1
            if current_span_length < shortest_span_length:
                shortest_span_length = current_span_length

    return shortest_span_length

Big(O) Analysis

Time Complexity
O(n) – First, we iterate through the array of size n once to populate our frequency, first-occurrence, and last-occurrence hash maps, taking constant time per element. Next, we iterate through the unique keys stored in our maps, where the number of unique keys is at most n, to calculate the span for each candidate element. The total operations scale linearly as n plus the number of unique elements, which simplifies to O(n).
Space Complexity
O(N) – The auxiliary space is driven by three hash maps that store the frequency, first occurrence index, and last occurrence index for each distinct element in the collection. In the worst-case scenario where all N elements are completely unique, each hash map will grow to store N entries. Therefore, the memory consumed by these tracking dictionaries scales linearly with the input size N, simplifying to Big O notation of O(N).

Edge Cases

Minimum-sized input with a single element
How to Handle:
The degree is 1, so the shortest contiguous subarray of that degree is 1, which the algorithm computes correctly by returning the difference between the first and last indices plus one.
Array where all elements are unique
How to Handle:
Every element has a frequency of 1, the degree is 1, and the algorithm correctly identifies 1 as the minimum length by taking the first occurrence of any element.
Array with multiple elements sharing the maximum frequency
How to Handle:
We track the maximum frequency globally and update the minimum length whenever any element matches or exceeds the current degree, correctly capturing all candidates.
Input containing negative numbers, zeros, and positive integers
How to Handle:
Using hash maps or hash tables instead of direct index arrays allows the solution to seamlessly handle arbitrary integer ranges without out-of-bounds errors.
Array with all elements identical
How to Handle:
The degree equals the length of the array, and the algorithm returns the full array length since the first and last indices span the entire input.
Maximum-sized input arrays leading to large memory or time constraints
How to Handle:
A single-pass or two-pass approach using hash maps runs in O(N) time and O(N) space, scaling efficiently to meet performance requirements.
Extreme boundary values for integers
How to Handle:
Standard hash map implementations natively support all 32-bit or 64-bit signed integers as keys without causing overflow issues.
Non-empty constraint violation as described in the problem statement
How to Handle:
Since the input is guaranteed to be non-empty, we do not need special guards for empty arrays and can safely initialize our tracking variables.
0/3 completed