algoadvance

Leetcode 697. Degree of an Array

Problem Statement

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.

Clarifying Questions

  1. What can we assume about the input array?
    • The array nums will be non-empty and consists of non-negative integers.
  2. What should be the output?
    • The length of the smallest contiguous subarray that has the same degree as the original array.
  3. Are there any constraints on the size of the array?
    • No specific constraints mentioned. Typically, we can assume it to be up to (10^5) given the nature of array problems on LeetCode.

Strategy

  1. Degree Calculation:
    • First, calculate the frequency of each element in the array to determine the degree of the array.
  2. Track Occurrences:
    • Use a hash map to store the first and last occurrence (indices) of each element.
  3. Find Minimum Length Subarray:
    • Iterate through the frequency map and determine the minimum length of the subarray for elements that have the frequency equal to the degree.

Code

import java.util.HashMap;

class Solution {
    public int findShortestSubArray(int[] nums) {
        // Maps to store the first and last positions, and the count of elements
        HashMap<Integer, Integer> left = new HashMap<>();
        HashMap<Integer, Integer> right = new HashMap<>();
        HashMap<Integer, Integer> count = new HashMap<>();
        
        int degree = 0;
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if (!left.containsKey(num)) {
                left.put(num, i);
            }
            right.put(num, i);
            count.put(num, count.getOrDefault(num, 0) + 1);
            degree = Math.max(degree, count.get(num));
        }
        
        int minLength = nums.length;
        for (Integer num : count.keySet()) {
            if (count.get(num) == degree) {
                minLength = Math.min(minLength, right.get(num) - left.get(num) + 1);
            }
        }
        
        return minLength;
    }
}

Time Complexity

This approach efficiently calculates the required smallest subarray with a degree equal to that of the array with optimal time and space usage.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI