Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
Example 1:
Input: nums = [1,2,2,3,1] Output: 2 Explanation: The input array has a degree of 2 because both elements 1 and 2 appear twice. Of the subarrays that have the same degree: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] The shortest length is 2. So return 2.
Example 2:
Input: nums = [1,2,2,3,1,4,2] Output: 6 Explanation: The degree is 3 because the element 2 is repeated 3 times. So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.
Constraints:
nums.length will be between 1 and 50,000.nums[i] will be an integer between 0 and 49,999.Problem summary: Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
[1,2,2,3,1]
[1,2,2,3,1,4,2]
maximum-subarray)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #697: Degree of an Array
class Solution {
public int findShortestSubArray(int[] nums) {
Map<Integer, Integer> cnt = new HashMap<>();
Map<Integer, Integer> left = new HashMap<>();
Map<Integer, Integer> right = new HashMap<>();
int degree = 0;
for (int i = 0; i < nums.length; ++i) {
int v = nums[i];
cnt.put(v, cnt.getOrDefault(v, 0) + 1);
degree = Math.max(degree, cnt.get(v));
if (!left.containsKey(v)) {
left.put(v, i);
}
right.put(v, i);
}
int ans = 1000000;
for (int v : nums) {
if (cnt.get(v) == degree) {
int t = right.get(v) - left.get(v) + 1;
if (ans > t) {
ans = t;
}
}
}
return ans;
}
}
// Accepted solution for LeetCode #697: Degree of an Array
func findShortestSubArray(nums []int) int {
cnt := map[int]int{}
left := map[int]int{}
right := map[int]int{}
var degree int
for i, v := range nums {
cnt[v]++
if degree < cnt[v] {
degree = cnt[v]
}
if _, ok := left[v]; !ok {
left[v] = i
}
right[v] = i
}
ans := 100000
for v, c := range cnt {
if c == degree {
t := right[v] - left[v] + 1
if ans > t {
ans = t
}
}
}
return ans
}
# Accepted solution for LeetCode #697: Degree of an Array
class Solution:
def findShortestSubArray(self, nums: List[int]) -> int:
cnt = Counter(nums)
degree = cnt.most_common()[0][1]
left, right = {}, {}
for i, v in enumerate(nums):
if v not in left:
left[v] = i
right[v] = i
ans = inf
for v in nums:
if cnt[v] == degree:
t = right[v] - left[v] + 1
if ans > t:
ans = t
return ans
// Accepted solution for LeetCode #697: Degree of an Array
struct Solution;
struct Degree {
left: usize,
right: usize,
count: usize,
}
use std::collections::HashMap;
use std::usize;
impl Solution {
fn find_shortest_sub_array(nums: Vec<i32>) -> i32 {
let mut hm: HashMap<i32, Degree> = HashMap::new();
let n = nums.len();
let mut max_degree: usize = 0;
for i in 0..n {
let x = nums[i];
let e = hm.entry(x).or_insert(Degree {
left: i,
right: i,
count: 0,
});
e.left = usize::min(e.left, i);
e.right = usize::max(e.right, i);
e.count += 1;
max_degree = usize::max(e.count, max_degree);
}
let mut min_width: usize = n;
for d in hm.values() {
if d.count == max_degree {
min_width = usize::min(d.right - d.left + 1, min_width);
}
}
min_width as i32
}
}
#[test]
fn test() {
let nums = vec![1, 2, 2, 3, 1];
assert_eq!(Solution::find_shortest_sub_array(nums), 2);
let nums = vec![1, 2, 2, 3, 1, 4, 2];
assert_eq!(Solution::find_shortest_sub_array(nums), 6);
}
// Accepted solution for LeetCode #697: Degree of an Array
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #697: Degree of an Array
// class Solution {
// public int findShortestSubArray(int[] nums) {
// Map<Integer, Integer> cnt = new HashMap<>();
// Map<Integer, Integer> left = new HashMap<>();
// Map<Integer, Integer> right = new HashMap<>();
// int degree = 0;
// for (int i = 0; i < nums.length; ++i) {
// int v = nums[i];
// cnt.put(v, cnt.getOrDefault(v, 0) + 1);
// degree = Math.max(degree, cnt.get(v));
// if (!left.containsKey(v)) {
// left.put(v, i);
// }
// right.put(v, i);
// }
// int ans = 1000000;
// for (int v : nums) {
// if (cnt.get(v) == degree) {
// int t = right.get(v) - left.get(v) + 1;
// if (ans > t) {
// ans = t;
// }
// }
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.