Ways to Split Array Into Good Subarrays - Multiply Index Differences [JS]

Description 

Solution: Multiply Index Differences

  1. Collect the indexes of all 1's.
  2. Multiply the index difference between each adjacent pair of 1's.

e.g: 010001
The difference between the first pair of 1's = 4
This indicates 4 different places to split:

  • 01|0001
  • 010|001
  • 0100|01
  • 01000|1

We do the same for each other adjacent pair of 1's and multiply the differences together to get the total combinations.

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

var numberOfGoodSubarraySplits = function(nums) {
  let n = nums.length, MOD = 10 ** 9 + 7, ones = [];
  for (let i = 0; i < n; i++) {
    if (nums[i] === 1) ones.push(i);
  }
  if (!ones.length) return 0;
  let ans = 1;
  for (let i = 1; i < ones.length; i++) {
    let ways = ones[i] - ones[i - 1];
    ans = (ans * ways) % MOD;
  }
  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]