Skip to main content

Sum of Beautiful Subsequences - Solution & Explanation

HardArrayMathBinary Indexed TreeNumber Theory4 min readAsked at: Infosys, Google
Practice this problem

Problem Statement

You are given an integer array nums of length n.

For every positive integer g, we define the beauty of g as the product of g and the number of strictly increasing subsequences of nums whose greatest common divisor (GCD) is exactly g.

Return the sum of beauty values for all positive integers g.

Since the answer could be very large, return it modulo 109 + 7.

 

Example 1:

Input: nums = [1,2,3]

Output: 10

Explanation:

All strictly increasing subsequences and their GCDs are:

Subsequence GCD
[1] 1
[2] 2
[3] 3
[1,2] 1
[1,3] 1
[2,3] 1
[1,2,3] 1

Calculating beauty for each GCD:

GCD Count of subsequences Beauty (GCD × Count)
1 5 1 × 5 = 5
2 1 2 × 1 = 2
3 1 3 × 1 = 3

Total beauty is 5 + 2 + 3 = 10.

Example 2:

Input: nums = [4,6]

Output: 12

Explanation:

All strictly increasing subsequences and their GCDs are:

Subsequence GCD
[4] 4
[6] 6
[4,6] 2

Calculating beauty for each GCD:

GCD Count of subsequences Beauty (GCD × Count)
2 1 2 × 1 = 2
4 1 4 × 1 = 4
6 1 6 × 1 = 6

Total beauty is 2 + 4 + 6 = 12.

 

Constraints:

  • 1 <= n == nums.length <= 104
  • 1 <= nums[i] <= 7 * 104

Approach Overview

Problem Overview: You are given an array and must compute the total sum contributed by all beautiful subsequences. A subsequence becomes beautiful based on a mathematical property between its elements (typically divisibility or gcd relationships). The challenge is that the number of subsequences grows exponentially, so you must aggregate contributions efficiently instead of enumerating them.

Approach 1: Brute Force Subsequence Enumeration (O(2^n * n) time, O(n) space)

Generate every possible subsequence using recursion or bitmasking. For each subsequence, check whether it satisfies the beauty condition using a mathematical check such as gcd or divisor relations. If it is valid, compute its contribution to the final sum. This approach directly models the definition of the problem but quickly becomes infeasible once n exceeds ~20 because the number of subsequences doubles with every element.

Approach 2: Dynamic Programming with Divisor Enumeration (O(n * sqrt(V)) time, O(V) space)

Instead of generating subsequences explicitly, track how many valid subsequences end with a given value. For each number x, enumerate its divisors and update dynamic programming states representing subsequences whose last element maintains the beauty condition. The key insight: subsequences that remain beautiful often depend only on shared divisibility or gcd relationships. This allows transitions from previous compatible values to the current value without recomputing the whole subsequence. The DP array stores counts or sums of subsequences grouped by value.

Approach 3: Fenwick Tree (Binary Indexed Tree) + Number Theory (O(n log V) time, O(V) space)

The optimal solution uses a Binary Indexed Tree to maintain prefix aggregates of subsequence contributions indexed by value. For each element a[i], compute all relevant divisors using number theory techniques. Query the Fenwick tree to retrieve the total contribution from previously processed elements that can extend into a beautiful subsequence with a[i]. Update the structure with the new subsequences formed by including a[i]. This avoids scanning all previous elements and reduces transitions to logarithmic time.

The Fenwick tree efficiently supports prefix sum queries and updates, making it ideal when subsequence transitions depend on ordered values. Combined with divisor enumeration, it compresses what would otherwise be quadratic DP into near-linear time.

Recommended for interviews: Start by explaining the brute force enumeration to show you understand subsequences and the beauty condition. Then move to the optimized dynamic programming idea. Interviewers typically expect the Fenwick Tree + number theory optimization because it reduces the transition cost and scales to large arrays.

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Subsequence EnumerationO(2^n * n)O(n)Only for very small arrays or when validating logic
DP with Divisor EnumerationO(n * sqrt(V))O(V)Medium constraints where divisor enumeration is manageable
Fenwick Tree + Number TheoryO(n log V)O(V)Large inputs where fast range aggregation is required

Video Solution

3671. Sum of Beautiful Subsequences (Leetcode Hard)Programming Live with Larry500 views views

Frequently Asked Questions

Is Sum of Beautiful Subsequences easy or hard?
Sum of Beautiful Subsequences is classified as a hard problem because it combines multiple advanced ideas: subsequence dynamic programming, number theory observations, and Fenwick Tree optimization. Recognizing how to aggregate subsequence contributions efficiently is the main challenge.
Sum of Beautiful Subsequences Python/Java solution
A typical implementation builds a Fenwick Tree array and processes elements sequentially. For each value, query compatible ranges or divisor-based states, compute the number or sum of subsequences ending at that value, and update the tree. The same algorithm translates directly to Python, Java, C++, and Go.
How to solve Sum of Beautiful Subsequences in O(n log V)?
Process the array from left to right and maintain a Fenwick Tree indexed by values. For each number, compute compatible values using divisor relationships or gcd-based rules. Query the tree to obtain contributions from previous elements, form new subsequences including the current number, then update the tree with the new contribution.
What is the best approach for Sum of Beautiful Subsequences?
The most efficient solution uses dynamic programming combined with a Binary Indexed Tree (Fenwick Tree) and number theory observations. Each element extends previously valid subsequences whose values satisfy the beauty condition, and the Fenwick Tree stores prefix aggregates for fast transitions. This reduces the complexity to about O(n log V), which works for large constraints.
Is Sum of Beautiful Subsequences asked at Google/Amazon/Meta?
Problems combining subsequences with number theory and Fenwick Trees appear frequently in interviews at companies like Google, Amazon, and Meta. The exact problem title may vary, but the underlying pattern—DP over values with prefix aggregation—is a common advanced interview topic.
What data structure is used in Sum of Beautiful Subsequences?
The optimized solution relies on a Binary Indexed Tree (Fenwick Tree) to maintain prefix sums of subsequence contributions. Number theory utilities such as divisor enumeration or gcd computations are also used to determine valid transitions between elements.
What is the time complexity of Sum of Beautiful Subsequences?
The optimal approach runs in O(n log V) time, where n is the array length and V is the maximum value in the array. The logarithmic factor comes from Fenwick Tree updates and queries. Space complexity is O(V) to maintain aggregated subsequence contributions by value.

Ready to solve this problem?

Practice Sum of Beautiful Subsequences with our built-in code editor and test cases.

Practice on FleetCode