Ways to Split Array Into Good Subarrays - Multiply Index Differences [JS]
Solution: Multiply Index Differences
- Collect the indexes of all 1's.
- 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
Post a Comment