Magicsheet logo

Degree of an Array

Easy
48.5%
Updated 6/1/2025

Degree of an Array

What is this problem about?

The Degree of an Array interview question gives you a non-empty array of non-negative integers. The "degree" of the array is the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a contiguous subarray that has the same degree as the original array. This Degree of an Array coding problem is about identifying the "span" of the most frequent elements.

Why is this asked in interviews?

Companies like Salesforce and JPMorgan use this to test a candidate's proficiency with Hash Tables. It requires you to track multiple pieces of information simultaneously: the frequency of each number, and its first and last seen indices. It evaluates your ability to process an array in a single pass to collect all necessary metrics.

Algorithmic pattern used

This follows the Array, Hash Table interview pattern.

  1. Three-Map Logic: Use one map for frequency, one for the first_occurrence index, and one for the last_occurrence index.
  2. Single Pass: Iterate through the array once, updating all three maps.
  3. Degree Calculation: Find the maximum value in the frequency map.
  4. Minimal Length: For all elements that have a frequency equal to the degree, calculate last_occurrence - first_occurrence + 1. The minimum of these spans is the answer.

Example explanation

nums = [1, 2, 2, 3, 1]

  • '1': freq=2, first=0, last=4. Span = 5.
  • '2': freq=2, first=1, last=2. Span = 2.
  • '3': freq=1, first=3, last=3. Span = 1. The degree is 2 (for '1' and '2'). The spans for degree-2 elements are 5 and 2. The minimum is 2.

Common mistakes candidates make

  • Sub-optimal Complexity: Attempting to find every subarray and check its degree (O(N^3) or O(N^2)).
  • Multiple Passes: Iterating through the array three separate times when one pass is sufficient to populate all maps.
  • Span calculation: Forgetting to add +1 when calculating the length from indices.

Interview preparation tip

When you need to know the range or count of elements, a Hash Map is your best tool. Practice solving problems where the map value is an object or a tuple, allowing you to store complex state for each key.

Similar Questions