Count the Number of Good Partitions - Two Pointers [JS]

Description 

Solution: Two Pointers

  1. Find the number of groups.
  • All occurances of a number must be contained in the same group.
  • Use two pointers to find the number of groups:
    • Record the indices of the last occurance of each number.
    • Extend the right pointer of the group to lastIndex[nums[i]], until the left pointer reaches the right pointer.
  1. Calculate the number of different partitions of these groups.
  • Each group has two choices: Either join the current group with the previous group, or start a new partition.
  • Since the first group has only one choice, it can be calculated as: 2^(groups - 1). Calculate this on the fly.

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

var numberOfGoodPartitions = function(nums) {
  let n = nums.length, lastIndex = {};
  for (let i = 0; i < n; i++) {
    lastIndex[nums[i]] = i;
  }
  let i = 0, foundFirstGroup = false;
  let ans = 1n, MOD = 1000000007n;
  while (i < n) {
    let j = lastIndex[nums[i]];
    while (i < j) {
      i++;
      j = Math.max(j, lastIndex[nums[i]]);
    }
    if (foundFirstGroup) {
      ans = (ans * 2n) % MOD;
    }
    i++, foundFirstGroup = true;
  }
  return ans;
};

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]