Skip to content

1157. Online Majority Element In Subarray 👍

  • Time:
    • Constructor: $O(n)$
    • query(left: int, right: int, threshold: int): $O(\log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class MajorityChecker {
 public:
  MajorityChecker(vector<int>& arr) : arr(arr) {
    for (int i = 0; i < arr.size(); ++i)
      numToIndices[arr[i]].push_back(i);
  }

  int query(int left, int right, int threshold) {
    for (int i = 0; i < kTimes; ++i) {
      const int randIndex = rand() % (right - left + 1) + left;
      const int num = arr[randIndex];
      const vector<int>& indices = numToIndices[num];
      const auto lit = ranges::lower_bound(indices, left);
      const auto rit = ranges::upper_bound(indices, right);
      if (rit - lit >= threshold)
        return num;
    }

    return -1;
  }

 private:
  const vector<int> arr;
  static constexpr int kTimes = 20;  // 2^kTimes >> |arr| = n
  unordered_map<int, vector<int>> numToIndices;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class MajorityChecker {
  public MajorityChecker(int[] arr) {
    this.arr = arr;
    for (int i = 0; i < arr.length; ++i) {
      if (!numToIndices.containsKey(arr[i]))
        numToIndices.put(arr[i], new ArrayList<>());
      numToIndices.get(arr[i]).add(i);
    }
  }

  public int query(int left, int right, int threshold) {
    for (int i = 0; i < kTimes; ++i) {
      final int randIndex = rand.nextInt(right - left + 1) + left;
      final int num = arr[randIndex];
      List<Integer> indices = numToIndices.get(num);
      final int l = firstGreaterEqual(indices, left);
      final int r = firstGreaterEqual(indices, right + 1);
      if (r - l >= threshold)
        return num;
    }

    return -1;
  }

  private static final int kTimes = 20; // 2^kTimes >> |arr|
  private int[] arr;
  private Map<Integer, List<Integer>> numToIndices = new HashMap<>();
  private Random rand = new Random();

  private int firstGreaterEqual(List<Integer> A, int target) {
    final int i = Collections.binarySearch(A, target);
    return i < 0 ? -i - 1 : i;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class MajorityChecker:
  def __init__(self, arr: list[int]):
    self.arr = arr
    self.kTimes = 20  # 2^kTimes >> |arr|
    self.numToIndices = collections.defaultdict(list)

    for i, a in enumerate(self.arr):
      self.numToIndices[a].append(i)

  def query(self, left: int, right: int, threshold: int) -> int:
    for _ in range(self.kTimes):
      randIndex = random.randint(left, right)
      num = self.arr[randIndex]
      indices = self.numToIndices[num]
      l = bisect.bisect_left(indices, left)
      r = bisect.bisect_right(indices, right)
      if r - l >= threshold:
        return num

    return -1