LeetCode 697: Degree of an Array Solution

Master LeetCode problem 697 (Degree of an Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

697. Degree of an Array

Problem Explanation

Explanation

To find the smallest possible length of a subarray with the same degree as the given array, we need to find the degree of the array (maximum frequency of any element), and then find the shortest subarray that contains the same degree element(s).

  1. Find the degree of the array by counting the frequencies of each element.
  2. For each element that has the maximum frequency, calculate the smallest subarray that contains all occurrences of that element.
  3. Return the length of the shortest subarray found.

Time Complexity: O(n), where n is the number of elements in the array
Space Complexity: O(n) for storing element frequencies

Solution Code

class Solution {
    public int findShortestSubArray(int[] nums) {
        Map<Integer, Integer> count = new HashMap<>();
        Map<Integer, Integer> firstIndex = new HashMap<>();
        int degree = 0;
        int minLength = Integer.MAX_VALUE;

        for (int i = 0; i < nums.length; i++) {
            firstIndex.putIfAbsent(nums[i], i);
            count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);
            if (count.get(nums[i]) > degree) {
                degree = count.get(nums[i]);
            }
        }

        for (int num : count.keySet()) {
            if (count.get(num) == degree) {
                minLength = Math.min(minLength, firstIndex.get(num) - firstIndex.get(num) + 1);
            }
        }

        return minLength;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 697 (Degree of an Array)?

This page provides optimized solutions for LeetCode problem 697 (Degree of an Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 697 (Degree of an Array)?

The time complexity for LeetCode 697 (Degree of an Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 697 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 697 in Java, C++, or Python.

Back to LeetCode Solutions