116. Degree of an Array

Easy · Array

The degree of an array is the maximum frequency of any element in it. Given an array of positive integers, find the length of the shortest contiguous subarray that has the same degree as the original array.

For example, in [1,2,2,3,1], the degree is 2 (both 1 and 2 appear twice). The shortest subarray with degree 2 is [2,2], which has length 2.

Input: an array of positive integers. Output: an integer representing the length of the shortest contiguous subarray with the same degree as the input array.

Examples

Example 1
Input: [1, 2, 2, 3, 1]
Output: 2
Explanation: Element 2 has degree 2 and its shortest window is [2,2]
Example 2
Input: [1, 2, 2, 3, 1, 4, 2]
Output: 6
Explanation: Element 2 has degree 3; shortest window covering all three 2s has length 6

Constraints