Count Ways to Choose Coprime Integers from Rows Problem
Description
LeetCode Problem 3725.
You are given a m x n matrix mat of positive integers.
Return an integer denoting the number of ways to choose exactly one integer from each row of mat such that the greatest common divisor of all chosen integers is 1.
Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: mat = [[1,2],[3,4]]
Output: 3
Explanation:
Chosen integer in the first row Chosen integer in the second row Greatest common divisor of chosen integers
1 3 1
1 4 1
2 3 1
2 4 2
3 of these combinations have a greatest common divisor of 1. Therefore, the answer is 3.
Example 2:
Input: mat = [[2,2],[2,2]]
Output: 0
Explanation:
Every combination has a greatest common divisor of 2. Therefore, the answer is 0.
Constraints:
1 <= m == mat.length <= 1501 <= n == mat[i].length <= 1501 <= mat[i][j] <= 150
Solution
Approach: DP over the gcd
Only the gcd of the chosen numbers matters, and every value is at most 150. Let dp[g] be the number of ways to pick one number from each row processed so far so that their gcd is g. Start with dp[0] = 1, because gcd(0, v) = v.
For each row, count how many times each value v occurs, then for every g with dp[g] > 0 and every value v present in the row, add dp[g] * cnt[v] to next[gcd(g, v)], modulo 10^9 + 7. After the last row, the answer is dp[1].
Complexity: time O(m * 150 * 150 * log 150), space O(150), where m is the number of rows.
from math import gcd
class Solution:
def countCoprime(self, mat: List[List[int]]) -> int:
mod = 10**9 + 7
mx = 150
dp = [0] * (mx + 1)
dp[0] = 1
for row in mat:
cnt = [0] * (mx + 1)
for v in row:
cnt[v] += 1
nxt = [0] * (mx + 1)
for g in range(mx + 1):
if dp[g] == 0:
continue
for v in range(1, mx + 1):
if cnt[v]:
h = gcd(g, v)
nxt[h] = (nxt[h] + dp[g] * cnt[v]) % mod
dp = nxt
return dp[1]