Search topics...

Degree of an Array

easy
arrayTime: O(n)Space: O(n)Frequency: 3

Given a non-empty array, find the smallest length of a contiguous subarray that has the same degree as the array.

Example 1:

Input: nums = [1, 2, 2, 3, 1]
Output: 2
Explanation: The degree is 2 (elements 1 and 2 both appear twice).
             The shortest subarray with degree 2 is [2, 2] with length 2.

Example 2:

Input: nums = [1, 2, 2, 3, 1, 4, 2]
Output: 6
Explanation: The degree is 3 (element 2 appears 3 times).
             The shortest subarray with degree 3 is [2, 2, 3, 1, 4, 2] with length 6.
hash-map