Leetcode #1819: Number of Different Subsequences GCDs
In this guide, we solve Leetcode #1819 Number of Different Subsequences GCDs in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, Math, Counting, Number Theory
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
Input: nums = [6,10,3]
Output: 5
Explanation: The figure shows all the non-empty subsequences and their GCDs.
The different GCDs are 6, 10, 3, 2, and 1.
Python Solution
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
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.