![]() |
VOOZH | about |
Given an array arr[] of size n and an integer k, determine the number of elements that appear more than n/k times in the array.
Examples:
Input: arr[ ] = [3, 4, 2, 2, 1, 2, 3, 3], k = 4
Output: 2
Explanation: Here n/k is 8/4 = 2, therefore 2 appears 3 times in the array that is greater than 2 and 3 appears 3 times in the array that is greater than 2Input: arr[ ] = [9, 10, 7, 9, 2, 9, 10], k = 3
Output: 1
Explanation: Here n/k is 7/3 = 2, therefore 9 appears 3 times in the array that is greater than 2.
The idea is to pick all elements one by one. For every picked element, count its occurrences by traversing the array, if count becomes more than n/k, then print the element.
2
The idea is to apply Moore's Voting algorithm, as there can be at max k - 1 elements present in the array which appears more than n/k times so their will be k - 1 candidates. When we encounter an element which is one of our candidates then increment the count else decrement the count.
Illustration:
Consider k = 4, n = 9
Given array: 3 1 2 2 2 1 4 3 3i = 0
temp[] has one element {3} with count 1i = 1
temp[] has two elements {3, 1} with counts 1 and 1 respectivelyi = 2
temp[] has three elements, {3, 1, 2} with counts as 1, 1 and 1 respectively.i = 3
temp[] has three elements, {3, 1, 2} with counts as 1, 1 and 2 respectively.i = 4
temp[] has three elements, {3, 1, 2} with counts as 1, 1 and 3 respectively.i = 5
temp[] has three elements, {3, 1, 2 with counts as 1, 2 and 3 respectively.i = 6
temp[] has two elements, {1, 2} with counts as 1 and 2 respectively.i = 7
temp[] has three elements, {3, 1, 2} with counts as 1, 1 and 2 respectively.i = 8
temp[] has three elements, {3, 1, 2} with counts as 2, 1 and 2 respectively.
Follow the steps below to solve the problem:
Number:3 Count:3 Number:2 Count:3
Time Complexity: O(n * k), Checking for each element of the array(size N) in the candidate array of size K
Auxiliary Space: O(k) Space required to store the candidates.
This approach is same the first approach but here in python there is a counter() that calculates the frequency array.
3 2