Problem solution · Python

Count Ways to Choose Coprime Integers from Rows

Count Ways to Choose Coprime Integers from Rows: a Python solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Dynamic programming
Source
Kamyu LeetCode Solutions
Length
75 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Count Ways to Choose Coprime Integers from Rows, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 75 lines of Python from the credited upstream file count-ways-to-choose-coprime-integers-from-rows.py.
  • The implementation visibly relies on sequence storage, hash lookup, cached states.
  • No explicit loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeCount Ways to Choose Coprime Integers from Rows · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n * (m + rlogr)), r = max(max(row) for row in mat)# Space: O(r) import collections  # dp, number theory, mobius function, principle of inclusion-exclusion, freq tableclass Solution(object):    def countCoprime(self, mat):        """        :type mat: List[List[int]]        :rtype: int        """        MOD = 10**9+7        def linear_sieve_of_eratosthenes(n):  # Time: O(n), Space: O(n)            primes = []            spf = [-1]*(n+1)  # the smallest prime factor            for i in xrange(2, n+1):                if spf[i] == -1:                    spf[i] = i                    primes.append(i)                for p in primes:                    if i*p > n or p > spf[i]:                        break                    spf[i*p] = p            return spf         # https://www.geeksforgeeks.org/program-for-mobius-function-set-2/        def mobius(spf):  # Time: O(n), Space: O(n)            mu = [0]*len(spf)            for i in xrange(1, len(mu)):                mu[i] = 1 if i == 1 else 0 if spf[i//spf[i]] == spf[i] else -mu[i//spf[i]]            return mu         mx = max(max(row) for row in mat)        mu = mobius(linear_sieve_of_eratosthenes(mx))        dp = [1]*(mx+1)        for row in mat:            cnt = collections.defaultdict(int)            for x in row:                cnt[x] += 1            for i in xrange(1, mx+1):                dp[i] = (dp[i]*reduce(lambda accu, x: (accu+x)%MOD, (cnt[j] for j in xrange(i, mx+1, i)), 0))%MOD        return reduce(lambda accu, x: (accu+x)%MOD, (dp[i]*mu[i] for i in xrange(1, mx+1)), 0)  # Time:  O(n * m * rlogr)# Space: O(r)import collections  # dp, number thoeryclass Solution2(object):    def countCoprime(self, mat):        """        :type mat: List[List[int]]        :rtype: int        """        MOD = 10**9+7        def gcd(a, b):            while b:                a, b = b, a%b            return a         dp = collections.defaultdict(int)        dp[0] = 1        for row in mat:            new_dp = collections.defaultdict(int)            for x in row:                for g, c in dp.iteritems():                    ng = gcd(g, x)                    new_dp[ng] = (new_dp[ng]+c)%MOD            dp = new_dp        return dp[1] 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗