#697
Easy Algorithms Degree of an array
Array Hash Table
58.2% acceptance
Feb 20, 2026
3261
1810
Given a non-empty array of non-negative integers nums, find the smallest
length subarray with the same degree as nums.
Solution
Rust
Time O(n)
Space O(n)
use std::collections::HashMap;
impl Solution {
pub fn find_shortest_sub_array(nums: Vec<i32>) -> i32 {
let mut count: HashMap<i32, i32> = HashMap::new();
let mut first: HashMap<i32, usize> = HashMap::new();
let mut last: HashMap<i32, usize> = HashMap::new();
for (i, &n) in nums.iter().enumerate() {
*count.entry(n).or_insert(0) += 1;
first.entry(n).or_insert(i);
last.insert(n, i);
}
let degree = *count.values().max().unwrap();
count.iter()
.filter(|&(_, &c)| c == degree)
.map(|(&n, _)| (last[&n] - first[&n] + 1) as i32)
.min()
.unwrap()
}
}