2022-11-12 Daily Challenge

Today I have done leetcode's November LeetCoding Challenge with cpp.

November LeetCoding Challenge 12

Description

Find Median from Data Stream

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.

  • For example, for arr = [2,3,4], the median is 3.
  • For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.

Implement the MedianFinder class:

  • MedianFinder() initializes the MedianFinder object.
  • void addNum(int num) adds the integer num from the data stream to the data structure.
  • double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.

 

Example 1:

Input
["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []]
Output
[null, null, null, 1.5, null, 2.0]

Explanation
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1);    // arr = [1]
medianFinder.addNum(2);    // arr = [1, 2]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3);    // arr[1, 2, 3]
medianFinder.findMedian(); // return 2.0

 

Constraints:

  • -105 <= num <= 105
  • There will be at least one element in the data structure before calling findMedian.
  • At most 5 * 104 calls will be made to addNum and findMedian.

 

Follow up:

  • If all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
  • If 99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?

Solution

auto speedup = [](){
  cin.tie(nullptr);
  cout.tie(nullptr);
  ios::sync_with_stdio(false);
  return 0;
}();
#define lowbit(x) (x & (-x))
const int SIZE = 200002;
int BITS[SIZE];
void add(int x) {
  while(x < SIZE) {
    BITS[x] += 1;
    x += lowbit(x);
  }
}
int sum(int x) {
  int result = 0;
  while(x) {
    result += BITS[x];
    x -= lowbit(x);
  }
  return result;
}
class MedianFinder {
  int size = 0;
  int low = INT_MAX;
  int high = INT_MIN;
  int get(int cnt) {
    int start = low;
    int end = high;
    while(start < end) {
      int mid = (start + end) >> 1;
      if(sum(mid) < cnt) {
        start = mid + 1;
      } else {
        end = mid;
      }
    }
    return start;
  }
public:
  /** initialize your data structure here. */
  MedianFinder() { 
    memset(BITS, 0, sizeof(BITS));
  }
  
  void addNum(int num) {
    low = min(low, num + 100001);
    high = max(high, num + 100001);
    size += 1;
    add(num + 100001);
  }
  
  double findMedian() {
    if(low == high) return low - 100001;
    if(size & 1) return get(size / 2 + 1) - 100001;
    return (get(size / 2) + get(size / 2 + 1)) / 2.0 - 100001;
  }
};

// 21/21 cases passed (363 ms)
// Your runtime beats 90.42 % of cpp submissions
// Your memory usage beats 100 % of cpp submissions (115.3 MB)