80. Degree Span

A weather station logs one sensor code per minute, stored in the array nums. The degree of a stretch of the log is the largest number of times any single code appears inside that stretch. A technician wants to replay the shortest possible contiguous stretch whose degree equals the degree of the entire log, so the most frequent code is still fully represented in it. Return the length of that shortest contiguous stretch.

If several codes tie for the highest count in the whole log, the stretch may be built around any one of them; only the smallest resulting length matters.

Example 1

Input:
nums = [4,7,7,9,4,2,7]
Output:
6
Explanation:

Code 7 appears 3 times (degree 3); its first and last positions are 1 and 6, so the shortest segment has length 6.

Example 2

Input:
nums = [5,5,8,8,3]
Output:
2
Explanation:

Codes 5 and 8 both appear twice; the segment [5,5] (or [8,8]) has length 2.

Constraints

1 ≤ nums.length ≤ 5 * 104

-109 ≤ nums[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…