Degree of an Array

Easy Arrays & Hashing Hashing

Degree of an Array is a easy arrays & hashing problem solved with the hashing pattern. The best approach, optimal (one pass with first index and count), runs in O(n) time and O(n) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from count, then scan for each most-frequent value up.

Problem

The degree of an array is the highest number of times any single value occurs in it. Given a non-empty array of non-negative integers nums, find the shortest contiguous subarray whose degree equals the degree of the whole array, and return its length.

Examples

Example 1

Input
nums = [4, 7, 7, 4, 2, 7]
Output
5
Why
7 appears 3 times, so the degree is 3. The shortest window holding all three 7s runs from index 1 to index 5, which is 5 elements.

Example 2

Input
nums = [3, 1, 3, 1, 5]
Output
3
Why
Both 3 and 1 appear twice. The window for 3 is [3, 1, 3] and the window for 1 is [1, 3, 1]; each has length 3.

Example 3

Input
nums = [9]
Output
1
Why
A single element has degree 1, and the array itself is the only window.

Constraints

  • 1 <= nums.length <= 5 * 10^4
  • 0 <= nums[i] < 5 * 10^4

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 47 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Count, then scan for each most-frequent valueO(n * k)O(n)
Optimal (one pass with first index and count)O(n)O(n)

1Count, then scan for each most-frequent value

TimeO(n * k)k is the number of values tied for the degree; when all values are distinct, k = n and this is O(n²).
SpaceO(n)

Count every value to find the degree. Then, for each value whose count equals the degree, scan the array to find its first and last positions; the span between them is a candidate answer.

  1. Build a frequency map and take the maximum count as the degree.
  2. For each value v with count == degree, scan the array for its first and last index.
  3. Answer = min over those values of last - first + 1.
class Solution {
    public int findShortestSubArray(int[] nums) {
        Map<Integer, Integer> count = new HashMap<>();
        int degree = 0;
        for (int x : nums) {
            int c = count.merge(x, 1, Integer::sum);
            degree = Math.max(degree, c);
        }
        int best = nums.length;
        for (Map.Entry<Integer, Integer> e : count.entrySet()) {
            if (e.getValue() != degree) continue;
            int v = e.getKey(), first = -1, last = -1;
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == v) {
                    if (first == -1) first = i;
                    last = i;
                }
            }
            best = Math.min(best, last - first + 1);
        }
        return best;
    }
}

2Optimal (one pass with first index and count)

TimeO(n)One pass with constant-time map operations.
SpaceO(n)Two maps keyed by the distinct values.

Walk the array once. For each value remember where it first appeared and how many times it has been seen so far. When a value's count beats the current degree, its span from first index to here becomes the answer; when it ties the degree, keep the shorter span.

  1. Keep maps first[v] and count[v], plus degree = 0 and best = 0.
  2. At index i with value v: set first[v] if missing, increment count[v], and let span = i - first[v] + 1.
  3. If count[v] > degree: degree = count[v], best = span. Else if count[v] == degree: best = min(best, span).
  4. Return best.
class Solution {
    public int findShortestSubArray(int[] nums) {
        Map<Integer, Integer> first = new HashMap<>();
        Map<Integer, Integer> count = new HashMap<>();
        int degree = 0, best = 0;
        for (int i = 0; i < nums.length; i++) {
            int v = nums[i];
            first.putIfAbsent(v, i);
            int c = count.merge(v, 1, Integer::sum);
            int span = i - first.get(v) + 1;
            if (c > degree) {
                degree = c;
                best = span;
            } else if (c == degree) {
                best = Math.min(best, span);
            }
        }
        return best;
    }
}

Edge cases to test

  • A single element
  • All elements distinct (degree 1, answer 1)
  • All elements equal (answer is the whole array)
  • Several values tie for the highest frequency; pick the one with the tightest span

Hints

Hint 1

A subarray with the same degree must contain every copy of some most-frequent value.

Hint 2

So the best window for a value v starts at its first occurrence and ends at its last.

Hint 3

Record the first index and the count of every value in one pass; update the answer whenever a count reaches or ties the current maximum.

FAQ

What is the best time complexity for Degree of an Array?

Optimal (one pass with first index and count) runs in O(n) time and O(n) extra space. One pass with constant-time map operations.

Which pattern does Degree of an Array use?

It is a arrays & hashing problem that uses the hashing pattern. Other problems with the same pattern: Group Anagrams, First Unique Character in a String, Number of Matching Subsequences.

Is there a brute force solution for Degree of an Array?

Yes. Count, then scan for each most-frequent value takes O(n * k) time and O(n) space. Count every value to find the degree.

Which edge cases should I test for Degree of an Array?

A single element; All elements distinct (degree 1, answer 1); All elements equal (answer is the whole array); Several values tie for the highest frequency; pick the one with the tightest span.