Advertisement

Online Majority Element In Subarray - LeetCode 1157 Solution

Online Majority Element In Subarray - Complete Solution Guide

Online Majority Element In Subarray is LeetCode problem 1157, a Hard level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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

Detailed Explanation

The problem requires designing a data structure, `MajorityChecker`, that can efficiently find the majority element within a given subarray of an input array. A majority element is defined as an element that appears at least `threshold` times within the specified subarray. The `MajorityChecker` class has two methods: `__init__(arr)` to initialize the data structure with the input array `arr`, and `query(left, right, threshold)` to return the majority element in the subarray `arr[left...right]` if it exists (i.e., its count is >= `threshold`), otherwise return -1. Constraints are provided to limit the size of the array and number of queries, as well as relationships between `left`, `right`, and `threshold` to help with solution design.

Solution Approach

The solution employs a probabilistic approach combined with binary search. It first preprocesses the input array to store the indices of each element in a hash map (`locs`). When a query is received, it randomly picks a few indices within the subarray, treating the corresponding elements as potential candidates for the majority element. For each candidate, it uses binary search on the pre-computed index list to count the number of occurrences of the candidate within the specified range [left, right]. If the count is greater than or equal to the given threshold, it returns the candidate. After a fixed number of attempts (30 in this implementation), if no majority element is found, it returns -1.

Step-by-Step Algorithm

  1. Step 1: **Initialization:** Create a hash map (`locs`) where keys are elements of the array and values are lists of their indices in the array. This is done during the `MajorityChecker` object construction.
  2. Step 2: **Query Processing:** For each `query(left, right, threshold)`: Repeat the following steps a fixed number of times (e.g., 30):
  3. Step 3: **Random Candidate Selection:** Pick a random index `rand_idx` within the range `[left, right]`.
  4. Step 4: **Occurrence Counting:** Get the element `candidate` at index `rand_idx`. Use binary search on the list of indices stored in `locs[candidate]` to find the number of occurrences of `candidate` within the range `[left, right]`.
  5. Step 5: **Threshold Check:** If the count of `candidate` is greater than or equal to `threshold`, return `candidate` as the majority element.
  6. Step 6: **No Majority Element Found:** If after the fixed number of attempts, no majority element is found, return -1.

Key Insights

  • Insight 1: The constraint `2 * threshold > right - left + 1` implies that if a majority element exists, it must appear more than 50% of the time within the subarray. This greatly simplifies the search because if we pick enough random indices within the subarray, we are highly likely to stumble upon the majority element, if one exists.
  • Insight 2: Storing the indices of each element in the original array allows for efficient counting of occurrences of a candidate element within the given subarray using binary search.
  • Insight 3: Using a probabilistic approach (randomly picking candidates) combined with binary search provides an efficient and practical solution to this problem.

Complexity Analysis

Time Complexity: O(log n)

Space Complexity: O(n)

Topics

This problem involves: Array, Binary Search, Design, Binary Indexed Tree, Segment Tree.

Companies

Asked at: Nutanix.