Number of Different Subsequences GCDs - 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.

  • For example, the GCD of the sequence [4,6,16] is 2.

A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.

  • For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].

Return the number of different GCDs among all non-empty subsequences of nums.

Input & Output

Example 1 — Small Array
$ Input: nums = [6,10,3]
Output: 5
💡 Note: All possible subsequences and their GCDs: [6]→6, [10]→10, [3]→3, [6,10]→2, [6,3]→3, [10,3]→1, [6,10,3]→1. Unique GCDs: {1,2,3,6,10}, so answer is 5.
Example 2 — Identical Elements
$ Input: nums = [5,15,40,5,6]
Output: 7
💡 Note: With elements 5,15,40,5,6, we can form subsequences with GCDs: 1,2,3,5,6,15,40. Total unique GCDs = 7.
Example 3 — Single Element
$ Input: nums = [42]
Output: 1
💡 Note: Only one subsequence [42] with GCD = 42. Answer is 1.

Constraints

  • 1 ≤ nums.length ≤ 103
  • 1 ≤ nums[i] ≤ 2 × 105

Visualization

Tap to expand
Number of Different Subsequences GCDs INPUT Array nums: 6 10 3 [0] [1] [2] Divisors: 6: 1,2,3,6 10: 1,2,5,10 3: 1,3 Candidate GCDs: 1 to 10 max(nums) = 10 Check each g from 1 to 10 if g can be GCD of subsequence ALGORITHM STEPS 1 Find max element maxVal = 10 2 Create presence set present = {3, 6, 10} 3 For each g: 1 to 10 Check multiples g,2g,3g... 4 Compute running GCD If GCD of multiples = g, count++ Verification Table g Multiples GCD=g? 1 3,6,10 OK 2 6,10 OK 3 3,6 OK 6 6 OK 10 10 OK 4,5,7-9 -- NO FINAL RESULT Valid GCDs Found: 1 2 3 6 10 Output: 5 Subsequence Examples: [6,10] --> GCD=2 [6,3] --> GCD=3 [6,10,3] --> GCD=1 [6],[10] --> GCD=6,10 Key Insight: Instead of checking all 2^n subsequences, iterate through each candidate GCD g from 1 to max(nums). For each g, check multiples (g, 2g, 3g...) present in array. If GCD of all present multiples equals g, then g is achievable. Time: O(max(nums) * log(max(nums)) + n), avoiding exponential complexity. TutorialsPoint - Number of Different Subsequences GCDs | Divisor-Based Approach
Asked in
Google 15 Amazon 12
25.0K Views
Medium Frequency
~35 min Avg. Time
890 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