Number of Different Subsequences GCDs — LeetCode 1819 Python Solution

HardArrayMathCountingNumber Theory
Problem
#1819
Reading time
3 min

The problem

You are given an array nums that consists of positive integers. The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly.

Example

Input
nums = [6,10,3]
Output
5
Explanation
The figure shows all the non-empty subsequences and their GCDs.

Python solution

Python
class Solution:
    def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int:
        mx = max(nums)
        vis = set(nums)
        ans = 0
        for x in range(1, mx + 1):
            g = 0
            for y in range(x, mx + 1, x):
                if y in vis:
                    g = gcd(g, y)
                    if g == x:
                        ans += 1
                        break
        return ans

Complexity

MeasureComplexity
TimeO(n + M \times \log M)
SpaceO(M) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1819. Number of Different Subsequences GCDs is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Number Theory.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1819. Number of Different Subsequences GCDs?
LeetCode 1819. Number of Different Subsequences GCDs is rated Hard on LeetCode.
What is the time complexity of LeetCode 1819. Number of Different Subsequences GCDs?
The Python solution on this page runs in O(n + M \times \log M).
What is the space complexity of LeetCode 1819. Number of Different Subsequences GCDs?
The Python solution on this page uses O(M) auxiliary space.
What topics does LeetCode 1819. Number of Different Subsequences GCDs cover?
LeetCode 1819. Number of Different Subsequences GCDs is tagged Array, Math, Counting and Number Theory on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview