Find the Median of the Uniqueness Array - Binary Search [JS]

Description 

Solution: Binary Search

Binary search for the smallest distinct count x where the number of subarrays with <= x distinct characters is less than the median number of subarrays.

To count the number of subarrays with less than or equal to x distinct characters, use a sliding window and a hashmap.
Count the number of subarrays ending at each index j, and move up the left pointer i if the number of distinct numbers exceeds x.

Time Complexity: O(n log(n))
Space Comlexity: O(n)

var medianOfUniquenessArray = function(nums) {
  let n = nums.length, totalSubarrays = n * (n + 1) / 2;
  let medianThreshold = Math.ceil(totalSubarrays / 2);
  let low = 1, high = n;
  while (low < high) {
    let mid = Math.floor((low + high) / 2);
    if (countSubarrays(mid) >= medianThreshold) high = mid;
    else low = mid + 1;
  }
  return low;
  
  function countSubarrays(maxDistinct) {
    let subarrays = 0, count = {}, distinct = 0;
    for (let i = 0, j = 0; j < n; j++) {
      count[nums[j]] = (count[nums[j]] || 0) + 1;
      if (count[nums[j]] === 1) distinct++;
      while (distinct > maxDistinct) {
        count[nums[i]]--;
        if (count[nums[i]] === 0) distinct--;
        i++;
      }
      subarrays += (j - i + 1);
    }
    return subarrays;
  }
};

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]