Count Ways to Choose Coprime Integers from Rows - Solution & Explanation
Problem Statement
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 109 + 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
Approach Overview
Problem Overview: You are given a matrix where each row contains several integers. Choose exactly one number from every row so that all selected numbers are pairwise coprime. The task is to count how many valid selections exist.
Approach 1: Brute Force Backtracking (Exponential Time, O(n^m))
The most direct strategy is to try every possible combination by picking one element from each row using recursion or backtracking. Maintain the current set of chosen numbers and verify that every new candidate keeps the set coprime by computing gcd(a, b). If the number conflicts with any previously selected value, skip it. This approach clearly demonstrates the constraint but becomes infeasible when rows or columns grow because the search space multiplies quickly. Time complexity is O(n^m) where m is the number of rows and n is the average row size, with O(m) auxiliary space for recursion.
Approach 2: Prime Factor Mask + Dynamic Programming (O(m * n * 2^k))
A better strategy comes from the number theory observation that two numbers are coprime when they share no common prime factor. Precompute the prime factorization of each number and encode it as a bitmask representing the primes it contains. While iterating through rows, maintain a DP state where mask represents the set of prime factors already used by previously chosen numbers.
For each row, try every value in that row. If the value’s prime mask does not intersect with the current mask (mask & valueMask == 0), it can be chosen safely. Transition to the next state by combining masks (mask | valueMask) and accumulate the number of ways. This converts the pairwise coprime constraint into a fast bitmask compatibility check. The complexity becomes O(m * n * 2^k), where k is the number of relevant primes (typically small), and space complexity is O(2^k).
Approach 3: Optimized DP with Precomputed Masks and Rolling States (O(m * n * 2^k))
The DP can be optimized further by compressing states between rows. Instead of storing a full 2D table, keep only the current mask counts and build the next row’s states using a temporary map or array. Precomputing prime masks once for all matrix values avoids repeated factorization. This reduces constant factors while preserving the same asymptotic complexity. The technique is common in problems mixing dynamic programming, bitmask state compression, and number theory.
Recommended for interviews: Start by describing the brute force search to show you understand the constraint. Then move to the prime-factor mask idea, which transforms coprime checking into a constant-time bit operation. Interviewers typically expect the DP with bitmask solution because it combines mathematical insight with efficient state transitions.
Solutions for this problem are being prepared.
Try solving it yourselfDetailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Backtracking | O(n^m) | O(m) | Small matrices or when explaining the base idea in interviews |
| Prime Factor Bitmask + DP | O(m * n * 2^k) | O(2^k) | General case where values have limited prime factors |
| Optimized Rolling DP | O(m * n * 2^k) | O(2^k) | Large matrices where memory and constant factors matter |
Video Solution
Count Ways to Choose Coprime Integers from Rows | LeetCode 3725 | Biweekly Contest 168 • Sanyam IIT Guwahati • 628 views views
Watch 3 more video solutions →Frequently Asked Questions
Is Count Ways to Choose Coprime Integers from Rows easy or hard?
Count Ways to Choose Coprime Integers from Rows Python/Java solution
How to solve Count Ways to Choose Coprime Integers from Rows in O(n)?
What is the best approach for Count Ways to Choose Coprime Integers from Rows?
Is Count Ways to Choose Coprime Integers from Rows asked at Google/Amazon/Meta?
What data structure is used in Count Ways to Choose Coprime Integers from Rows?
What is the time complexity of Count Ways to Choose Coprime Integers from Rows?
Ready to solve this problem?
Practice Count Ways to Choose Coprime Integers from Rows with our built-in code editor and test cases.
Practice on FleetCodeProblem Info
Table of Contents
Practice this problem
Open in Editor