#2584
Split the Array to Make Coprime Products
HardArrayHash TableMathNumber TheoryHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * log(max(nums))) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * log(max(nums)))Space O(n)
Instead of calculating products directly, we can use prime factorization to check for common prime factors. This reduces the need for repeated calculations and allows us to efficiently determine coprimality.
⚙️
Algorithm
4 steps- 1Step 1: Create a function to get the prime factors of a number.
- 2Step 2: Use two sets to track prime factors for the left and right segments as we iterate through the array.
- 3Step 3: For each split index, check if the sets of prime factors intersect. If they do not, return the index.
- 4Step 4: If no valid split is found, return -1.
solution.py26 lines
1from collections import defaultdict
2
3def prime_factors(n):
4 factors = set()
5 for i in range(2, int(n**0.5) + 1):
6 while n % i == 0:
7 factors.add(i)
8 n //= i
9 if n > 1:
10 factors.add(n)
11 return factors
12
13def find_valid_split(nums):
14 n = len(nums)
15 left_factors = set()
16 total_factors = defaultdict(int)
17 for num in nums:
18 for factor in prime_factors(num):
19 total_factors[factor] += 1
20 for i in range(n - 1):
21 for factor in prime_factors(nums[i]):
22 left_factors.add(factor)
23 total_factors[factor] -= 1
24 if all(total_factors[factor] == 0 for factor in left_factors):
25 return i
26 return -1ℹ
Complexity note: The complexity arises from factorizing each number, which takes logarithmic time relative to the number's value, and we do this for each element in the array.
- 1Understanding coprimality through prime factors can simplify the problem.
- 2Using sets to track prime factors allows for efficient checking of overlaps.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.