Split the Array to Make Coprime Products — LeetCode 2584 Python Solution
- Problem
- #2584
- Pattern
- Math and Number Theory
- Reading time
- 5 min
- Source
- leetcode.com
The problem
You are given a 0-indexed integer array nums of length n. A split at an index i where 0 <= i <= n - 2 is called valid if the product of the first i + 1 elements and the product of the remaining elements are coprime.
Example
- Input
- nums = [4,7,8,15,3,5]
- Output
- 2
- Explanation
- The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i.
Python solution
class Solution:
def findValidSplit(self, nums: List[int]) -> int:
first = {}
n = len(nums)
last = list(range(n))
for i, x in enumerate(nums):
j = 2
while j <= x // j:
if x % j == 0:
if j in first:
last[first[j]] = i
else:
first[j] = i
while x % j == 0:
x //= j
j += 1
if x > 1:
if x in first:
last[first[x]] = i
else:
first[x] = i
mx = last[0]
for i, x in enumerate(last):
if mx < i:
return mx
mx = max(mx, x)
return -1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2584. Split the Array to Make Coprime Products is filed here because LeetCode tags it Math and Number Theory, which is the vocabulary this hub collects.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2584. Split the Array to Make Coprime Products?
- LeetCode 2584. Split the Array to Make Coprime Products is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2584. Split the Array to Make Coprime Products?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2584. Split the Array to Make Coprime Products?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2584. Split the Array to Make Coprime Products cover?
- LeetCode 2584. Split the Array to Make Coprime Products is tagged Array, Hash Table, Math and Number Theory on LeetCode.