LeetCode - Degree of an Array Java - The Coding Shala
Home >> LeetCode >> degree of an array
LeetCode - Degree of an Array
In this post, you will learn how to find the Degree of an Array. Here we will implement LeetCode's Degree of an array solution in Java.
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.
Input: [1, 2, 2, 3, 1]
The input array has a degree of 2 because both elements 1 and 2 appear twice. 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.
Practice this problem on LeetCode: Click Here
Degree of an Array Java Solution
To solve this problem in need to count occurrences of each element in the array and then the distance between the left index and right index of max occurred number. if the count of two elements is the same then we need to return minimum distance. We can solve this using HashMap.
Time Complexity: O(N)
Space Complexity: O(N), space used by HashMap.
Other Posts You May Like
- LeetCode - Contains Duplicate
- LeetCode - Climbing Stairs
- LeetCode - Swap Nodes in Pairs
- LeetCode - Jewels and Stones
- Hackerrank - Minimum Swaps