Leetcode

Online Majority Element In Subarray

  • Time:Constructor: O(n), query(left: int, right: int, threshold: int): O(\log n)
  • Space:O(n)

C++

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 auto& 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;
};

JAVA

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;
  }
}

Python

class MajorityChecker:
  def __init__(self, arr: List[int]):
    self.A = arr
    self.kTimes = 20  # 2^kTimes >> len(A)
    self.numToIndices = 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