Talentd
FleetCode

1157. Online Majority Element In Subarray

Hard40.9% acceptance1 company

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 array arr.
  • int query(int left, int right, int threshold) returns the element in the subarray arr[left...right] that occurs at least threshold times, or -1 if 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 * 104
  • 1 <= arr[i] <= 2 * 104
  • 0 <= left <= right < arr.length
  • threshold <= right - left + 1
  • 2 * threshold > right - left + 1
  • At most 104 calls will be made to query.

Asked at 1 company

Hints open one at a time

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.
6:05
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class MajorityChecker:
2
3 def __init__(self, arr: List[int]):
4
5
6 def query(self, left: int, right: int, threshold: int) -> int:
7
8
9
10# Your MajorityChecker object will be instantiated and called as such:
11# obj = MajorityChecker(arr)
12# param_1 = obj.query(left,right,threshold)
Starter codePython 3Spaces: 4
Examples
Input
["MajorityChecker","query","query","query"]
[[[1,1,2,2,1,1]],[0,5,4],[0,3,3],[2,3,2]]
Your code is saved on this device.Solution