Number of Different Subsequences GCDs - Problem

Given an array nums of positive integers, you need to find how many different GCD values can be formed by all possible non-empty subsequences.

What is GCD? The Greatest Common Divisor (GCD) of a sequence is the largest positive integer that divides all numbers in the sequence evenly. For example, GCD([4, 6, 16]) = 2 because 2 is the largest number that divides 4, 6, and 16.

What is a subsequence? A subsequence is formed by removing some (possibly zero) elements from the original array while maintaining the relative order. For example, [2, 5, 10] is a subsequence of [1, 2, 1, 2, 4, 1, 5, 10].

Your task: Count how many distinct GCD values are possible among all non-empty subsequences of the given array.

Input & Output

example_1.py β€” Basic Case
$ Input: [6,10,3]
β€Ί Output: 4
πŸ’‘ Note: All possible subsequences: [6](GCD=6), [10](GCD=10), [3](GCD=3), [6,10](GCD=2), [6,3](GCD=3), [10,3](GCD=1), [6,10,3](GCD=1). Unique GCDs: {1,2,3,6} = 4 different values
example_2.py β€” Single Element
$ Input: [5]
β€Ί Output: 1
πŸ’‘ Note: Only one subsequence [5] with GCD=5, so answer is 1
example_3.py β€” Multiple Same Elements
$ Input: [4,4,4]
β€Ί Output: 1
πŸ’‘ Note: All subsequences have the same GCD=4, regardless of how many 4's we pick

Constraints

  • 1 ≀ nums.length ≀ 1000
  • 1 ≀ nums[i] ≀ 2 Γ— 105
  • All elements in nums are positive integers

Visualization

Tap to expand
πŸ—ΊοΈ GCD Treasure Hunt6103Available NumbersHunt GCD=2Multiples of 2:[6,10] β†’ GCD=2 βœ“Hunt GCD=3Multiples of 3:[6,3] β†’ GCD=3 βœ“βœ“ Found: 1βœ“ Found: 2βœ“ Found: 3βœ“ Found: 6πŸ† Total Treasures: 4GCDs Found: {1, 2, 3, 6}
Understanding the Visualization
1
Setup Treasure Map
Mark all numbers present in our array and find the highest number (our search boundary)
2
Visit Each Treasure
For each potential GCD from 1 to max, collect all its multiples from our array
3
Verify Treasure
Calculate the GCD of collected multiples. If it equals our target, we found a valid treasure!
4
Count Treasures
Sum up all valid GCD treasures we successfully found
Key Takeaway
🎯 Key Insight: Rather than exploring all 2^n possible subsequences (exponential time), we intelligently check each of the at most max(nums) possible GCD values, making the solution much more efficient!
Asked in
Google 23 Microsoft 15 Amazon 12 Meta 8
28.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen