Solving LeetCode Problem #697: Degree of an Array with Java

🚀 Day 32 of #100DaysOfCode – LeetCode Problem #697: Degree of an Array 🧩 Problem: Given a non-empty array of non-negative integers, the degree of the array is the maximum frequency of any element. The goal is to find the smallest possible length of a contiguous subarray that has the same degree as the entire array. 💡 Approach: To solve this efficiently: Track the first and last occurrence of each element. Track their frequency count. Identify elements that contribute to the array’s maximum degree. For each of those elements, compute the subarray length = last[i] - first[i] + 1. Return the minimum of those lengths. 💻 Java Code: class Solution { public int findShortestSubArray(int[] nums) { Map<Integer, Integer> count = new HashMap<>(); Map<Integer, Integer> first = new HashMap<>(); int degree = 0, bestLen = nums.length; for (int i = 0; i < nums.length; i++) { int num = nums[i]; first.putIfAbsent(num, i); count.put(num, count.getOrDefault(num, 0) + 1); degree = Math.max(degree, count.get(num)); } for (int i = 0; i < nums.length; i++) { int num = nums[i]; if (count.get(num) == degree) { int len = i - first.get(num) + 1; bestLen = Math.min(bestLen, len); } } return bestLen; } } ⏱️ Complexity: Time: O(n) Space: O(n) ✅ Result: Accepted (Runtime: 0 ms) This problem beautifully blends hashmaps and frequency analysis to derive insights efficiently — a perfect example of thinking beyond brute force!

To view or add a comment, sign in

Explore content categories