|
| 1 | +/** |
| 2 | + * 1157. Online Majority Element In Subarray |
| 3 | + * https://leetcode.com/problems/online-majority-element-in-subarray/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Design a data structure that efficiently finds the majority element of a given subarray. |
| 7 | + * |
| 8 | + * The majority element of a subarray is an element that occurs threshold times or more in |
| 9 | + * the subarray. |
| 10 | + * |
| 11 | + * Implementing the MajorityChecker class: |
| 12 | + * - MajorityChecker(int[] arr) Initializes the instance of the class with the given array arr. |
| 13 | + * - int query(int left, int right, int threshold) returns the element in the subarray |
| 14 | + * arr[left...right] that occurs at least threshold times, or -1 if no such element exists. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number[]} arr |
| 19 | + */ |
| 20 | +var MajorityChecker = function(arr) { |
| 21 | + this.positionMap = new Map(); |
| 22 | + this.array = arr; |
| 23 | + for (let i = 0; i < arr.length; i++) { |
| 24 | + const positions = this.positionMap.get(arr[i]) || []; |
| 25 | + positions.push(i); |
| 26 | + this.positionMap.set(arr[i], positions); |
| 27 | + } |
| 28 | +}; |
| 29 | + |
| 30 | +/** |
| 31 | + * @param {number} left |
| 32 | + * @param {number} right |
| 33 | + * @param {number} threshold |
| 34 | + * @return {number} |
| 35 | + */ |
| 36 | +MajorityChecker.prototype.query = function(left, right, threshold) { |
| 37 | + const maxAttempts = 20; |
| 38 | + const rangeLength = right - left + 1; |
| 39 | + |
| 40 | + for (let attempt = 0; attempt < maxAttempts; attempt++) { |
| 41 | + const candidate = this.array[left + Math.floor(Math.random() * rangeLength)]; |
| 42 | + const positions = this.positionMap.get(candidate); |
| 43 | + const count = countInRange(positions, left, right); |
| 44 | + |
| 45 | + if (count >= threshold) return candidate; |
| 46 | + if (count + rangeLength - count < threshold) return -1; |
| 47 | + } |
| 48 | + return -1; |
| 49 | +}; |
| 50 | + |
| 51 | +function countInRange(positions, left, right) { |
| 52 | + const leftIndex = lowerBound(positions, left); |
| 53 | + const rightIndex = upperBound(positions, right); |
| 54 | + return rightIndex - leftIndex; |
| 55 | +} |
| 56 | + |
| 57 | +function lowerBound(arr, target) { |
| 58 | + let start = 0; |
| 59 | + let end = arr.length; |
| 60 | + while (start < end) { |
| 61 | + const mid = Math.floor((start + end) / 2); |
| 62 | + if (arr[mid] < target) start = mid + 1; |
| 63 | + else end = mid; |
| 64 | + } |
| 65 | + return start; |
| 66 | +} |
| 67 | + |
| 68 | +function upperBound(arr, target) { |
| 69 | + let start = 0; |
| 70 | + let end = arr.length; |
| 71 | + while (start < end) { |
| 72 | + const mid = Math.floor((start + end) / 2); |
| 73 | + if (arr[mid] <= target) start = mid + 1; |
| 74 | + else end = mid; |
| 75 | + } |
| 76 | + return start; |
| 77 | +} |
0 commit comments