Class MajorityChecker

  • All Implemented Interfaces:

    
    public final class MajorityChecker
    
                        

    1157 - Online Majority Element In Subarray.

    Hard

    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:

    • <code>1 <= arr.length <= 2 * 10<sup>4</sup></code>

    • <code>1 <= arri<= 2 * 10<sup>4</sup></code>

    • 0 &lt;= left &lt;= right &lt; arr.length

    • threshold &lt;= right - left + 1

    • 2 * threshold &gt; right - left + 1

    • At most <code>10<sup>4</sup></code> calls will be made to query.

    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
    • Field Summary

      Fields 
      Modifier and Type Field Description
    • Enum Constant Summary

      Enum Constants 
      Enum Constant Description
    • Method Summary

      Modifier and Type Method Description
      final Integer query(Integer left, Integer right, Integer threshold)
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait