Problem
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 leastthreshold
times, or-1
if no such element exists.
Examples
Example 1:
|
|
Solution
Method 1 - Using binary search
To solve the problem of finding the majority element efficiently within a given subarray, we need a combination of:
- Pre-processing: Store information about the frequency of elements in the array.
- Querying: Use the pre-processed data to efficiently fetch the result for a subarray.
Approach
-
Pre-process the array:
- Use a map or dictionary to store the indices of each distinct element. For example, given the array
[1, 1, 2, 2, 1, 1]
, store the positions of1
as[0, 1, 4, 5]
, and2
as[2, 3]
. - This allows efficient querying of the positions where a specific element appears.
- Use a map or dictionary to store the indices of each distinct element. For example, given the array
-
Process the query:
- For a given subarray range (
left
,right
), check the frequencies of the potential majority elements. - Use binary search (via bisect) to count how many times the element appears within the range.
- If its frequency is greater than or equal to
threshold
, return the element; otherwise, return-1
.
- For a given subarray range (
The final structure allows for efficient querying by leveraging the pre-processed frequency data.
Code
|
|
|
|
Complexity
- ⏰ Time complexity: O(n)
, where
n` is the length of the array, to build the frequency map.- Query:
- For each query, checking the frequency using binary search takes
O(log(m))
, wherem
is the size of the positions list for an element. This process might repeat for multiple potential majority elements. - The worst case involves checking all unique elements, leading to
O(u * log(m))
, whereu
is the number of unique elements.
- For each query, checking the frequency using binary search takes
- Overall, querying is more efficient than a brute force approach.
- Query:
- 🧺 Space complexity:
O(n)
for storing element positions in the dictionary.