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
class MajorityChecker {
 public:
  MajorityChecker(vector<int>& arr) : A(arr) {
    for (int i = 0; i < A.size(); ++i)
      numToIndices[A[i]].push_back(i);
  }

  int query(int left, int right, int threshold) {
    for (int i = 0; i < kTimes; ++i) {
      const int num = A[rand() % A.size()];
      const vector<int>& indices = numToIndices[num];
      const auto lit = lower_bound(begin(indices), end(indices), left);
      const auto rit = upper_bound(begin(indices), end(indices), right);
      if (rit - lit >= threshold)
        return num;
    }

    return -1;
  }

 private:
  const vector<int> A;
  constexpr static int kTimes = 20;  // 2^kTimes >> A.size() = 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
class MajorityChecker {
  public MajorityChecker(int[] arr) {
    A = arr;
    for (int i = 0; i < A.length; ++i) {
      if (!numToIndices.containsKey(A[i]))
        numToIndices.put(A[i], new ArrayList<>());
      numToIndices.get(A[i]).add(i);
    }
  }

  public int query(int left, int right, int threshold) {
    for (int i = 0; i < kTimes; ++i) {
      final int num = A[rand.nextInt(A.length)];
      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 >> A.length
  private int[] A;
  private Map<Integer, List<Integer>> numToIndices = new HashMap<>();
  private Random rand = new Random();

  private int firstGreaterEqual(List<Integer> indices, int target) {
    int index = Collections.binarySearch(indices, target);
    return index < 0 ? -index - 1 : index;
  }
}
 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.A = arr
    self.kTimes = 20  # 2^kTimes >> len(A)
    self.numToIndices = collections.defaultdict(list)

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

  def query(self, left: int, right: int, threshold: int) -> int:
    for _ in range(self.kTimes):
      randIndex = randint(0, len(self.A) - 1)
      num = self.A[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