Online Majority Element In Subarray - 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.

Implement 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.

Input & Output

Example 1 — Basic Majority Check
$ Input: arr = [1,1,2,2,1,1], queries = [[0,5,4],[0,3,3],[2,3,2]]
Output: [1,-1,2]
💡 Note: Query [0,5,4]: Element 1 appears 4 times in full array (≥4). Query [0,3,3]: No element appears ≥3 times in [1,1,2,2]. Query [2,3,2]: Element 2 appears 2 times in [2,2] (≥2).
Example 2 — No Majority Found
$ Input: arr = [1,2,3,4,5], queries = [[0,4,3]]
Output: [-1]
💡 Note: In range [0,4], each element [1,2,3,4,5] appears only once, none meet threshold 3.
Example 3 — Small Range
$ Input: arr = [3,3,3], queries = [[0,2,2]]
Output: [3]
💡 Note: Element 3 appears 3 times in range [0,2], which is ≥ threshold 2.

Constraints

  • 1 ≤ arr.length ≤ 2 × 104
  • 1 ≤ arr[i] ≤ 2 × 104
  • 0 ≤ left ≤ right < arr.length
  • threshold ≤ right - left + 1
  • 1 ≤ queries ≤ 104

Visualization

Tap to expand
Online Majority Element In Subarray INPUT Array arr: 1 0 1 1 2 2 2 3 1 4 1 5 Queries: Q1: [0,5,4] left=0,right=5,th=4 Q2: [0,3,3] left=0,right=3,th=3 Q3: [2,3,2] left=2,right=3,th=2 Index Map Structure: 1 --> [0,1,4,5] 2 --> [2,3] ALGORITHM STEPS 1 Build Index Map Store positions for each unique element in array 2 Process Query For each query, check candidates in range 3 Binary Search Count Use binary search to count occurrences in [left,right] 4 Check Threshold Return element if count >= threshold, else -1 Example: Q1 [0,5,4] Range: arr[0..5] = [1,1,2,2,1,1] Count(1) = 4 >= 4 ? YES Result: 1 OK - Majority found! FINAL RESULT Query Results: Query 1: [0,5,4] Element 1 appears 4 times 1 Query 2: [0,3,3] No element appears 3+ times -1 Query 3: [2,3,2] Element 2 appears 2 times 2 Output Array: [1, -1, 2] Key Insight: Preprocessing with Index Maps allows O(1) lookup of all positions where each element appears. Binary search on sorted position lists enables efficient counting of occurrences in any range [left, right]. Time Complexity: O(n) preprocessing, O(k * log n) per query where k is number of unique elements to check. TutorialsPoint - Online Majority Element In Subarray | Index Maps + Binary Search Approach
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
23.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen