Skip to main content

Count Ways to Choose Coprime Integers from Rows - Solution & Explanation

Practice this problem

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 <= 150
  • 1 <= n == mat[i].length <= 150
  • 1 <= 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 yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force BacktrackingO(n^m)O(m)Small matrices or when explaining the base idea in interviews
Prime Factor Bitmask + DPO(m * n * 2^k)O(2^k)General case where values have limited prime factors
Optimized Rolling DPO(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 is classified as a Hard problem. It requires understanding number theory (prime factorization), dynamic programming, and bitmask state compression to efficiently enforce the pairwise coprime constraint.
Count Ways to Choose Coprime Integers from Rows Python/Java solution
Implementations typically precompute prime masks for each matrix value, then iterate row by row updating DP states. Python often uses dictionaries or arrays for mask counts, while Java and C++ commonly use integer arrays for faster transitions. The same bitmask DP logic applies across all languages.
How to solve Count Ways to Choose Coprime Integers from Rows in O(n)?
A pure O(n) solution is not typical because the problem requires exploring combinations across rows. The practical optimal solution uses dynamic programming with bitmask state compression. By representing prime factors as bitmasks and updating DP states row by row, the algorithm avoids exponential combination checks while keeping complexity manageable.
What is the best approach for Count Ways to Choose Coprime Integers from Rows?
The most efficient approach uses prime factorization with dynamic programming over bitmasks. Each number is converted into a mask representing its prime factors, and a DP state tracks which primes are already used by previously selected numbers. A number can be chosen only if its mask does not overlap with the current mask. This reduces coprime checks to constant-time bit operations.
Is Count Ways to Choose Coprime Integers from Rows asked at Google/Amazon/Meta?
Problems combining coprime constraints, dynamic programming, and bitmask optimization appear frequently in interviews at large tech companies. Variants involving prime factor masks, subset DP, or coprime selection are common in Google and Meta interview preparation sets.
What data structure is used in Count Ways to Choose Coprime Integers from Rows?
The solution mainly relies on arrays or hash maps for dynamic programming states and bitmasks to encode prime factors. Precomputed prime factorizations allow fast compatibility checks using bitwise AND operations.
What is the time complexity of Count Ways to Choose Coprime Integers from Rows?
The optimal dynamic programming approach runs in O(m * n * 2^k) time, where m is the number of rows, n is the average number of values per row, and k is the number of distinct primes considered. Space complexity is O(2^k) for storing DP states representing used prime factors.

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 FleetCode