Degree of an Array

EasyArrays & Hashingfrequency map

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

The **degree** of a non-empty array of non-negative integers is defined as the highest frequency of any single value within it. In other words, it is the count of the value that appears most often. Given an integer array nums, find the length of the **shortest contiguous subarray** that has the **same degree** as nums itself. Return that minimum length. A subarray is a slice of consecutive elements. Note that there may be several values that all share the maximum frequency, so you should consider each of them and keep the smallest qualifying window.

Examples

Input: nums = [1,2,2,3,1]
Output: 2
Both `1` and `2` appear twice, so the degree is `2`. The shortest subarray that still has degree `2` is `[2,2]`, which has length `2`. The window for `1` would be `[1,2,2,3,1]` with length `5`, so `2` is the minimum.
Input: nums = [1,2,2,3,1,4,2]
Output: 6
The value `2` appears three times, giving a degree of `3`. The shortest window containing all three `2`s spans from index 1 to index 6, which is `[2,2,3,1,4,2]` with length `6`.
Input: nums = [5]
Output: 1
A single element has degree `1`, and the whole array of length `1` is the only subarray with that degree.

Constraints

  • `1 <= nums.length <= 50000`
  • `0 <= nums[i] <= 49999`
  • The array is guaranteed to contain at least one element.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.