## Find the length of minimum sub array with maximum degree in an array

finding top 3 elements in array

finding top 3 repeated numbers in an array

findshortestsubarray leetcode

find symmetric pairs in an array

leet code degree of an array

in an array 1-100 exactly one number is duplicate how do you find it

first appearance of integer in an array

I tried solving a problem in hackerrank which is to find the length of minimum sub array with maximum degree in an array. The maximum degree of an array is the count of element with maximum frequency. For example, consider the example {2, 2, 1, 2, 3, 1, 1} the min sub-array length is 4 as 2 has the maximum degree and the smallest sub array which has degree 3 is {2, 2, 1, 2}

Below is my solution for the problem

public class FindingMinSubArrayWithDegree { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } System.out.println(degreeOfArray(arr)); sc.close(); } static int degreeOfArray(int[] arr) { HashMap<Integer, Integer> numbersByDegree = new HashMap<Integer, Integer>(); for (int i = 0; i < arr.length; i++) { int degree = numbersByDegree.getOrDefault(arr[i], 0); numbersByDegree.put(arr[i], degree + 1); } List<Map.Entry<Integer, Integer>> sortedEntries = sortByValue(numbersByDegree); int maxDegree = sortedEntries.get(0).getValue(); int[] degreeArr = new int[arr.length] ; int minSubArrayLength = arr.length; for (Map.Entry<Integer, Integer> entry : sortedEntries) { if (entry.getValue() < maxDegree) { break; } boolean startIndexFound = false, endIndexFound = false; int startIndex = 0, endIndex = 0; for (int i = 0; i < arr.length; i++) { if (entry.getKey() == arr[i]) { if (i - 1 >= 0) degreeArr[i] = degreeArr[i - 1] + 1; else degreeArr[i] = 1; } else { if (i - 1 >= 0) degreeArr[i] = degreeArr[i - 1]; } if (!startIndexFound && degreeArr[i] == 1) { startIndex = i; startIndexFound = true; } if (!endIndexFound && degreeArr[i] == entry.getValue()) { endIndex = i; endIndexFound = true; } if (startIndexFound && endIndexFound) break; } startIndexFound = false; endIndexFound = false; if ((endIndex - startIndex) < minSubArrayLength) { minSubArrayLength = endIndex - startIndex; } for (int i = 0; i < degreeArr.length; i++) degreeArr[i] = 0; } return minSubArrayLength + 1; } private static <K, V extends Comparable<? super V>> List<Map.Entry<K, V>> sortByValue(Map<K, V> map) { List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet()); Collections.sort( list, new Comparator<Map.Entry<K, V>>() { public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { return (o2.getValue()).compareTo( o1.getValue() ); } }); return list; } }

This approach has a worst case running time of O(N ^ 2) for inputs like { 1, 1, 2, 2, 3, 3, 4, 4} . Is there a better algorithm for this problem ?

PS - I tried asking this question in code review but didn't get any response that is why moved here

To find the degree of an array, we just need to keep track of the frequency of each distinct element in the array, and those elements that have the highest frequencies will be the degree.

So, to find the sub-array with the maximum degree, we only need to care about the subarray that contains the element that have the maximum counts, which means all the sub array with `[start , end]`

is the start and end occurrence of that element.

Thus, what we need to do is keeping track of frequency, start and end position of each element.

Pseudo code:

int max = 0; Map<Integer, Integer> map = new HashMap<>(); Map<Integer, Integer> startIndex = new HashMap<>(); Map<Integer, Integer> endIndex = new HashMap<>(); for(int i = 0; i < data.length; i++){ int value = data[i]; if(map.containsKey(value)){ map.put(value, map.get(value) + 1); }else{ startIndex.put(value, i); map.put(value, 1); } endIndex.put(value, i); max = Integer.max(max, map.get(value));//Calculate the degree of the array } int result = data.length; for(int i : map.keySet()){ if(map.get(i) == max){ int len = endIndex.get(i) - startIndex.get(i) + 1; result = Integer.min(result, len); } } return result;

Time complexity is O(n)

**Smallest subarray with all occurrences of a most frequent element ,** Find the smallest subsegment of the array which also has x as the maximum frequency element. Approach:Observe that if X is the maximum repeated element of our subsegment then To store length and starting index of. 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. Example 1:

**Degree of an Array,** 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 � I tried solving a problem in Hackerrank which is to find the length of minimum sub array with maximum degree in an array. For example, consider the example {2, 2, 1, 2, 3, 1, 1} the min sub-array length is 4 as 2 has the maximum degree and the smallest sub array which has degree 3 is {2, 2, 1, 2} Below is my solution for the problem:

**JavaScript Solution:**

function findShortestSubArray(nums) { // Elements is a map of key => elementInfo // with key being each of the elements in the array // and elementInfo being the object with properties count, leftIndex, rightIndex for // one particular element in the array let degree = 0 const elementsInfoHighestCount = new Map() let subArray = [] const elements = nums.reduce((acc, num, index) => { let count let leftIndex let rightIndex if (acc.has(num)) { const existing = acc.get(num) count = existing.count + 1 leftIndex = existing.leftIndex rightIndex = index } else { count = 1 leftIndex = index rightIndex = index } return acc.set(num, { count, leftIndex, rightIndex }) }, new Map()) // Determine the degree by looping through elements map elements.forEach((element, uniqueNum) => { if (element.count === degree) { elementsInfoHighestCount.set(uniqueNum, element) } else if (element.count > degree) { elementsInfoHighestCount.clear() elementsInfoHighestCount.set(uniqueNum, element) degree = element.count } }) // Get the shortest subarray array by looping through the elementInfoHighestCount map let result = elementsInfoHighestCount.values().next().value if (elementsInfoHighestCount.size === 1) { subArray = nums.slice(result.leftIndex, result.rightIndex + 1) } else if (elementsInfoHighestCount.size > 1) { elementsInfoHighestCount.forEach((element, num) => { const thisElementDiff = element.rightIndex - element.leftIndex const previousElementDiff = result.rightIndex - result.leftIndex if (thisElementDiff - previousElementDiff < 0) { result = elementsInfoHighestCount.get(num) } }) subArray = nums.slice(result.leftIndex, result.rightIndex + 1) } return subArray.length }; // Time complexity: O(N) // Testcases - [1, 2, 2, 3, 1], [1,2,2,3,1,4,2]

**Degree of an Array,** 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� Given an array of integers, find maximum length sub-array having given sum. We can use map to solve this problem in linear time. The idea is to create an empty map to store ending index of first sub-array having given sum. We traverse the given array, and maintain sum of elements seen so far.

**in Python:**

The degree of this array us defined as the max frequency of any of its elements. Note you need three dictionaries to hold counts and positions

def codeHere(arrayinput): numItems = len(arrayinput) degree = 0 left = dict() count = dict() right = dict() lenght = 0 result = numItems for i in range(numItems): x = arrayinput[i] if (x not in count): count[x] = 1 left[x] = i else: count[x] += 1 right[x] = i if (count[x] > degree): degree = count[x] for i in count.keys(): if(count[i] == degree): lenght=right[i] - left[i] + 1 if(lenght<result): result=lenght return (result)

**Solved: Given An Array Of N Integers, We Define Its Degree ,** I tried solving a problem in Hackerrank which is to find the length of minimum sub array with maximum degree in an array. For example� Given an array A having positive and negative integers and a number k, find the minimum length sub array of A with sum = k. Here is a video solution that finds minimum length sub array with sum = k explained with the help of examples and animations. Java code is provided in Code Snippet section.

**Degree of Array - Interview Question,** Answer to Given an array of n integers, we define its degree as the maximum We then return the minimum length of any subarray with a degree of 3, which is 4 � Find out the maximum sub-array of non negative numbers from an array. The sub-array should be continuous. That is, a sub-array created by choosing the second and fourth element and skipping the third element is invalid. Maximum sub-array is defined in terms of the sum of the elements in the sub-array. Sub-array A is greater than sub-array B if

**LeetCode – Minimum Size Subarray Sum (Java),** Find Degree of an Array and find minimum Sub Array with same Degree - Interview Duration: 8:56
Posted: Nov 8, 2018 Given an binary array containing 0 and 1, find maximum length sub-array having equal number of 0's and 1's. We can use map to solve this problem in linear time. The idea is to replace 0 with -1 and find out the largest subarray with 0 sum.

**The Maximum Subarray,** Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead. The maximum subsequence sum is comprised of element indices and the sum is . Function Description. Complete the maxSubarray function in the editor below. It should return an array of two integers: the maximum subarray sum and the maximum subsequence sum of . maxSubarray has the following parameter(s): arr: an array of integers

##### Comments

- What is
`degree`

of an array? - The degree of an array is the count of element with maximum frequency