1157. Online Majority Element In Subarray
Hard40.1% acceptance20,822 / 51,884 submissions
Asked by 1 company
Topics
Design a data structure that efficiently finds the majority element of a given subarray.
The majority element of a subarray is an element that occurs threshold times or more in the subarray.
Implementing the MajorityChecker class:
MajorityChecker(int[] arr)Initializes the instance of the class with the given arrayarr.int query(int left, int right, int threshold)returns the element in the subarrayarr[left...right]that occurs at leastthresholdtimes, or-1if no such element exists.
Example 1:
Input ["MajorityChecker", "query", "query", "query"] [[[1, 1, 2, 2, 1, 1]], [0, 5, 4], [0, 3, 3], [2, 3, 2]] Output [null, 1, -1, 2] Explanation MajorityChecker majorityChecker = new MajorityChecker([1, 1, 2, 2, 1, 1]); majorityChecker.query(0, 5, 4); // return 1 majorityChecker.query(0, 3, 3); // return -1 majorityChecker.query(2, 3, 2); // return 2
Constraints:
1 <= arr.length <= 2 * 1041 <= arr[i] <= 2 * 1040 <= left <= right < arr.lengththreshold <= right - left + 12 * threshold > right - left + 1- At most
104calls will be made toquery.
Hints
Hint 1
What's special about a majority element ?
Hint 2
A majority element appears more than half the length of the array number of times.
Hint 3
If we tried a random index of the array, what's the probability that this index has a majority element ?
Hint 4
It's more than 50% if that array has a majority element.
Hint 5
Try a random index for a proper number of times so that the probability of not finding the answer tends to zero.