We are given a read only array of n integers. Find any element that appears more than n/3 times in the array in linear time and constant additional space. If no such element exists, return -1.
Input : [10, 10, 20, 30, 10, 10] Output : 10 10 occurs 4 times which is more than 6/3. Input : [20, 30, 10, 10, 5, 4, 20, 1, 2] Output : -1
The idea is based on Moore’s Voting algorithm.
We first find two candidates. Then we check if any of these two candidates is actually a majority. Below is the solution for above approach.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Minimum peak elements from an array by their repeated removal at every iteration of the array
- Find maximum array sum after making all elements same with repeated subtraction
- Count of only repeated element in a sorted array of consecutive elements
- Smallest element in an array that is repeated exactly 'k' times.
- Maximum subarray sum in an array created after repeated concatenation
- Minimum array size after repeated replacement of even sum pair with sum
- Find top three repeated in array
- Largest element in the array that is repeated exactly k times
- Minimum count of elements required to obtain the given Array by repeated mirror operations
- Cost required to empty a given array by repeated removal of maximum obtained by given operations
- Make all array elements equal by repeated subtraction of absolute difference of pairs from their maximum
- Kth smallest element in the array using constant space when array can't be modified
- Minimum number of times A has to be repeated such that B is a substring of it
- Number of subsequences of maximum length K containing no repeated elements
- Smallest element repeated exactly ‘k’ times (not limited to small range)
- Construct binary palindrome by repeated appending and trimming
- Repeated Character Whose First Appearance is Leftmost
- Minimum cost to convert M to N by repeated addition of its even divisors
- Find the last remaining element after repeated removal of odd and even indexed elements alternately
- Rearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.