KatInterview

697. Degree of an Array

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method Explanation

This problem asks for the length of the shortest contiguous subarray that has the same "degree" as the original array. The degree is the maximum frequency of any element in the array.

Solution

Degree of an Array in Python

class Solution:
    def findShortestSubArray(self, nums: List[int]) -> int:
        # Stores the first occurrence index of each number
        left = {}
        # Stores the frequency of each number
        count = {}
        
        degree = 0
        min_length = 0

        for i, num in enumerate(nums):
            # Record the first occurrence of the number
            if num not in left:
                left[num] = i
            
            # Increment the count for the current number
            count[num] = count.get(num, 0) + 1
            
            # Check if this number sets a new degree
            if count[num] > degree:
                degree = count[num]
                min_length = i - left[num] + 1
            # Check if this number has the same degree, and if it provides a shorter subarray
            elif count[num] == degree:
                min_length = min(min_length, i - left[num] + 1)
        
        return min_length

Degree of an Array in Java

class Solution {
    public int findShortestSubArray(int[] nums) {
        // Map to store the first occurrence index of each number
        Map<Integer, Integer> left = new HashMap<>();
        // Map to store the frequency of each number
        Map<Integer, Integer> count = new HashMap<>();
        
        int degree = 0;
        int minLength = 0;

        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            
            // Record the first occurrence of the number
            // putIfAbsent ensures we only store the first index we see
            left.putIfAbsent(num, i);
            
            // Increment the count for the current number
            count.put(num, count.getOrDefault(num, 0) + 1);
            
            // Check if this number sets a new degree
            if (count.get(num) > degree) {
                degree = count.get(num);
                minLength = i - left.get(num) + 1;
            } 
            // Check if this number has the same degree, and if it provides a shorter subarray
            else if (count.get(num) == degree) {
                minLength = Math.min(minLength, i - left.get(num) + 1);
            }
        }
        
        return minLength;
    }
}

Degree of an Array in C++

class Solution {
public:
    int findShortestSubArray(vector<int>& nums) {
        // Map to store the first occurrence index of each number
        unordered_map<int, int> left;
        // Map to store the frequency of each number
        unordered_map<int, int> count;
        
        int degree = 0;
        int minLength = 0;

        for (int i = 0; i < nums.size(); ++i) {
            int num = nums[i];
            
            // Record the first occurrence of the number
            // if the number is not in the map, add it with the current index
            if (left.find(num) == left.end()) {
                left[num] = i;
            }
            
            // Increment the count for the current number
            count[num]++;
            
            // Check if this number sets a new degree
            if (count[num] > degree) {
                degree = count[num];
                minLength = i - left[num] + 1;
            } 
            // Check if this number has the same degree, and if it provides a shorter subarray
            else if (count[num] == degree) {
                minLength = min(minLength, i - left[num] + 1);
            }
        }
        
        return minLength;
    }
};

Degree of an Array in TypeScript

function findShortestSubArray(nums: number[]): number {
    // Map to store the first occurrence index of each number
    const left = new Map<number, number>();
    // Map to store the frequency of each number
    const count = new Map<number, number>();

    let degree = 0;
    let minLength = 0;

    for (let i = 0; i < nums.length; i++) {
        const num = nums[i];

        // Record the first occurrence of the number
        if (!left.has(num)) {
            left.set(num, i);
        }

        // Increment the count for the current number
        const currentCount = (count.get(num) || 0) + 1;
        count.set(num, currentCount);

        // Check if this number sets a new degree
        if (currentCount > degree) {
            degree = currentCount;
            // '!' non-null assertion because we know 'num' is in 'left' map
            minLength = i - left.get(num)! + 1;
        } 
        // Check if this number has the same degree, and if it provides a shorter subarray
        else if (currentCount === degree) {
            // '!' non-null assertion
            minLength = Math.min(minLength, i - left.get(num)! + 1);
        }
    }

    return minLength;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.