Split the Array to Make Coprime Products - Common Prime Factors [JS]

Description 

Solution: Common Prime Factors

Calculating the product creates numbers that are far too large.
Instead, get the prime factors of each number in the left and right sides and check if they share any common prime factors.
Keep the common prime factors in a hashset and remove prime factors when they are no longer shared.

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

var findValidSplit = function(nums) {
  let n = nums.length, right = {};
  for (let i = 0; i < n; i++) {
    let primeFactorsCount = getPrimeFactors(nums[i]);
    for (let prime in primeFactorsCount) {
      let count = primeFactorsCount[prime];
      right[prime] = (right[prime] || 0) + count;
    }
  }
  let left = {}, common = new Set();
  for (let i = 0; i <= n - 2; i++) {
    let primesFactorsCount = getPrimeFactors(nums[i]);
    for (let prime in primesFactorsCount) {
      let count = primesFactorsCount[prime];
      left[prime] = (left[prime] || 0) + count;
      right[prime] -= count;
      if (right[prime] > 0) common.add(prime);
      else if (right[prime] === 0) common.delete(prime);
    }
    if (common.size === 0) return i;
  }
  return -1;
};

function getPrimeFactors(n) {
  let counts = {};
  for (let x = 2; (x * x) <= n; x++) {
    while (n % x === 0) {
      counts[x] = (counts[x] || 0) + 1;
      n /= x;
    }
  }
  if (n > 1) counts[n] = (counts[n] || 0) + 1;
  return counts;
}

Comments

Popular posts from this blog

Beautiful Towers II - Monotonic Increasing Stack [JS]

Check if There is a Valid Partition For The Array - Two Approaches - DP & Recursion w/ Memoization [JS]

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Count Elements With Maximum Frequency - Hashmap [JS]

Mice and Cheese - Greedy w/ Sorting [JS]