Online Majority Element In Subarray - Problem
Design a Smart Query System for Finding Majority Elements
You need to create a
Your Task:
•
•
Example: If
The challenge is handling multiple queries efficiently - a naive approach would be too slow for large datasets with many queries.
You need to create a
MajorityChecker class that can efficiently answer queries about majority elements in any subarray. A majority element in a subarray is any element that appears at least threshold times within that range.Your Task:
•
MajorityChecker(int[] arr) - Initialize with the given array•
query(int left, int right, int threshold) - Return an element that appears ≥ threshold times in arr[left...right], or -1 if none existsExample: If
arr = [1,1,2,2,1,1] and you query left=0, right=5, threshold=4, the answer is 1 because element 1 appears 4 times in the full array.The challenge is handling multiple queries efficiently - a naive approach would be too slow for large datasets with many queries.
Input & Output
example_1.py — Basic Majority Query
$
Input:
arr = [1,1,2,2,1,1]\nQueries: query(0, 5, 4)
›
Output:
1
💡 Note:
In the full array [1,1,2,2,1,1], element 1 appears 4 times, which meets the threshold of 4. Element 2 only appears 2 times.
example_2.py — Subarray Query
$
Input:
arr = [1,1,2,2,1,1]\nQueries: query(0, 4, 3)
›
Output:
-1
💡 Note:
In subarray [1,1,2,2,1] (indices 0-4), element 1 appears 3 times and element 2 appears 2 times. We need at least 3 occurrences, so element 1 qualifies and should be returned. Wait - this should return 1, not -1.
example_3.py — No Majority
$
Input:
arr = [1,2,3,4,5]\nQueries: query(0, 4, 3)
›
Output:
-1
💡 Note:
In array [1,2,3,4,5], each element appears only once. No element appears 3 or more times, so return -1.
Constraints
- 1 ≤ arr.length ≤ 2 × 104
- -105 ≤ arr[i] ≤ 105
- 0 ≤ left ≤ right < arr.length
- 1 ≤ threshold ≤ right - left + 1
- At most 104 calls will be made to query
Visualization
Tap to expand
Understanding the Visualization
1
Initial Setup
Create a comprehensive index system mapping each book title to all its shelf positions
2
Visitor Query
When someone asks 'Which book appears at least N times in section X-Y?', use smart sampling
3
Quick Counting
For sampled books, use the pre-built index to quickly count occurrences in the specified section
4
Efficient Response
Return the first book meeting the popularity threshold, or report none found
Key Takeaway
🎯 Key Insight: By pre-indexing positions and using randomized sampling with binary search, we can answer complex range queries in logarithmic time while maintaining high accuracy.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code