#3725

Count Ways to Choose Coprime Integers from Rows

Hard
ArrayMathDynamic ProgrammingMatrixCombinatoricsNumber TheoryDynamic ProgrammingCombinatorics
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(m * n * log(max_value))
Space
O(1)
O(max_value)
💡

Intuition

Time O(m * n * log(max_value))Space O(max_value)

Use dynamic programming to track the number of ways to achieve each GCD as we process each row, avoiding redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP array to count ways for each GCD value.
  2. 2Step 2: For each row, update the DP array based on current integers and their GCDs.
  3. 3Step 3: Sum the counts for GCD value 1 from the DP array.
solution.py12 lines
1def countCoprime(mat):
2    from math import gcd
3    from collections import defaultdict
4    dp = defaultdict(int)
5    dp[0] = 1
6    for row in mat:
7        new_dp = defaultdict(int)
8        for num in row:
9            for g in dp:
10                new_dp[gcd(g, num)] = (new_dp[gcd(g, num)] + dp[g]) % (10**9 + 7)
11        dp = new_dp
12    return dp[1]

Complexity note: The time complexity is driven by iterating through each element and calculating GCD, while space is limited to the number of unique GCDs.

  • 1GCD properties help reduce combinations.
  • 2Dynamic programming can efficiently track states.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.