Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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 <= 1041 <= nums[i] <= 7 * 104Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math · Segment Tree
[1,2,3]
[4,6]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3671: Sum of Beautiful Subsequences
// Auto-generated Java example from go.
class Solution {
public void exampleSolution() {
}
}
// Reference (go):
// // Accepted solution for LeetCode #3671: Sum of Beautiful Subsequences
// package main
//
// import "slices"
//
// // https://space.bilibili.com/206214
// const mod = 1_000_000_007
// const mx = 70_001
//
// var divisors [mx][]int
//
// func init() {
// // 预处理每个数的因子
// for i := 1; i < mx; i++ {
// for j := i; j < mx; j += i { // 枚举 i 的倍数 j
// divisors[j] = append(divisors[j], i) // i 是 j 的因子
// }
// }
// }
//
// // 完整模板见 https://leetcode.cn/circle/discuss/mOr1u6/
// type fenwick []int
//
// func newFenwickTree(n int) fenwick {
// return make(fenwick, n+1) // 使用下标 1 到 n
// }
//
// // a[i] 增加 val
// // 1 <= i <= n
// // 时间复杂度 O(log n)
// func (f fenwick) update(i, val int) {
// for ; i < len(f); i += i & -i {
// f[i] += val
// }
// }
//
// // 求前缀和 a[1] + ... + a[i]
// // 1 <= i <= n
// // 时间复杂度 O(log n)
// func (f fenwick) pre(i int) (res int) {
// for ; i > 0; i &= i - 1 {
// res += f[i]
// }
// return res % mod
// }
//
// func totalBeauty(nums []int) (ans int) {
// m := slices.Max(nums)
//
// // 计算 b 的严格递增子序列的个数
// countIncreasingSubsequence := func(b []int, g int) (res int) {
// t := newFenwickTree(m / g)
// for _, x := range b {
// x /= g
// // cnt 表示以 x 结尾的严格递增子序列的个数
// cnt := t.pre(x-1) + 1 // +1 是因为 x 可以一个数组成一个子序列
// res += cnt
// t.update(x, cnt) // 更新以 x 结尾的严格递增子序列的个数
// }
// return res % mod
// }
//
// groups := make([][]int, m+1)
// for _, x := range nums {
// for _, d := range divisors[x] {
// groups[d] = append(groups[d], x)
// }
// }
//
// f := make([]int, m+1)
// for i := m; i > 0; i-- {
// f[i] = countIncreasingSubsequence(groups[i], i)
// // 倍数容斥
// for j := i * 2; j <= m; j += i {
// f[i] -= f[j]
// }
// // 注意 |f[i]| * i < mod * (m / i) * i = mod * m
// // m 个 mod * m 相加,至多为 mod * m * m,不会超过 64 位整数最大值
// ans += f[i] * i
// }
// // 保证结果非负
// return (ans%mod + mod) % mod
// }
// Accepted solution for LeetCode #3671: Sum of Beautiful Subsequences
package main
import "slices"
// https://space.bilibili.com/206214
const mod = 1_000_000_007
const mx = 70_001
var divisors [mx][]int
func init() {
// 预处理每个数的因子
for i := 1; i < mx; i++ {
for j := i; j < mx; j += i { // 枚举 i 的倍数 j
divisors[j] = append(divisors[j], i) // i 是 j 的因子
}
}
}
// 完整模板见 https://leetcode.cn/circle/discuss/mOr1u6/
type fenwick []int
func newFenwickTree(n int) fenwick {
return make(fenwick, n+1) // 使用下标 1 到 n
}
// a[i] 增加 val
// 1 <= i <= n
// 时间复杂度 O(log n)
func (f fenwick) update(i, val int) {
for ; i < len(f); i += i & -i {
f[i] += val
}
}
// 求前缀和 a[1] + ... + a[i]
// 1 <= i <= n
// 时间复杂度 O(log n)
func (f fenwick) pre(i int) (res int) {
for ; i > 0; i &= i - 1 {
res += f[i]
}
return res % mod
}
func totalBeauty(nums []int) (ans int) {
m := slices.Max(nums)
// 计算 b 的严格递增子序列的个数
countIncreasingSubsequence := func(b []int, g int) (res int) {
t := newFenwickTree(m / g)
for _, x := range b {
x /= g
// cnt 表示以 x 结尾的严格递增子序列的个数
cnt := t.pre(x-1) + 1 // +1 是因为 x 可以一个数组成一个子序列
res += cnt
t.update(x, cnt) // 更新以 x 结尾的严格递增子序列的个数
}
return res % mod
}
groups := make([][]int, m+1)
for _, x := range nums {
for _, d := range divisors[x] {
groups[d] = append(groups[d], x)
}
}
f := make([]int, m+1)
for i := m; i > 0; i-- {
f[i] = countIncreasingSubsequence(groups[i], i)
// 倍数容斥
for j := i * 2; j <= m; j += i {
f[i] -= f[j]
}
// 注意 |f[i]| * i < mod * (m / i) * i = mod * m
// m 个 mod * m 相加,至多为 mod * m * m,不会超过 64 位整数最大值
ans += f[i] * i
}
// 保证结果非负
return (ans%mod + mod) % mod
}
# Accepted solution for LeetCode #3671: Sum of Beautiful Subsequences
# Time: precompute: O(rlogr), r = max_nums
# runtime: O(mx + nlogr * (log(nlogr) + logn)), mx = max(nums)
# Space: O(rlogr)
# number theory, bit, fenwick tree
MOD = 10**9+7
class BIT(object): # 0-indexed.
def __init__(self, n):
self.__bit = [0]*(n+1) # Extra one for dummy node.
def add(self, i, val):
i += 1 # Extra one for dummy node.
while i < len(self.__bit):
self.__bit[i] = (self.__bit[i]+val) % MOD
i += (i & -i)
def query(self, i):
i += 1 # Extra one for dummy node.
ret = 0
while i > 0:
ret = (ret+self.__bit[i]) % MOD
i -= (i & -i)
return ret
def factors(n): # Time: O(nlogn)
result = [[] for _ in xrange(n+1)]
for i in xrange(1, n+1):
for j in range(i, n+1, i):
result[j].append(i)
return result
def phi_sieve(n): # Time: O(nlog(logn))
phi = range(n+1)
for i in xrange(2, n+1):
if phi[i] != i:
continue
for j in xrange(i, n+1, i):
phi[j] -= phi[j]//i
return phi
MAX_NUM = 7 * 10**4
FACTORS = factors(MAX_NUM)
PHI = phi_sieve(MAX_NUM)
class Solution(object):
def totalBeauty(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def count(arr):
for i, x in enumerate(sorted(arr)): # coordinate compression
val_to_idx[x] = i
bit = BIT(len(arr))
for x in arr:
bit.add(val_to_idx[x], bit.query(val_to_idx[x]-1)+1)
return bit.query(len(arr)-1)
mx = max(nums)
val_to_idx = [0]*(mx+1)
lookup = [[] for _ in xrange(mx+1)]
for x in nums:
for d in FACTORS[x]:
lookup[d].append(x)
return reduce(lambda accu, x: (accu+x)%MOD, (PHI[g]*count(lookup[g]) for g in reversed(xrange(1, mx+1))), 0)
# Time: precompute: O(rlogr), r = max_nums
# runtime: O(mx * log(mx) + nlogr * (log(nlogr) + logn)), mx = max(nums)
# Space: O(rlogr)
# number theory, bit, fenwick tree
class Solution2(object):
def totalBeauty(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def count(arr):
val_to_idx = {x:i for i, x in enumerate(sorted(set(arr)))} # coordinate compression
bit = BIT(len(val_to_idx))
for x in arr:
bit.add(val_to_idx[x], bit.query(val_to_idx[x]-1)+1)
return bit.query(len(val_to_idx)-1)
mx = max(nums)
lookup = [[] for _ in xrange(mx+1)]
for x in nums:
for d in FACTORS[x]:
lookup[d].append(x)
result = 0
cnt = [0]*(mx+1)
for g in reversed(xrange(1, mx+1)):
cnt[g] = count(lookup[g])
for ng in xrange(g+g, mx+1, g):
cnt[g] -= cnt[ng]
result = (result+g*cnt[g])%MOD
return result
// Accepted solution for LeetCode #3671: Sum of Beautiful Subsequences
// Rust example auto-generated from go reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (go):
// // Accepted solution for LeetCode #3671: Sum of Beautiful Subsequences
// package main
//
// import "slices"
//
// // https://space.bilibili.com/206214
// const mod = 1_000_000_007
// const mx = 70_001
//
// var divisors [mx][]int
//
// func init() {
// // 预处理每个数的因子
// for i := 1; i < mx; i++ {
// for j := i; j < mx; j += i { // 枚举 i 的倍数 j
// divisors[j] = append(divisors[j], i) // i 是 j 的因子
// }
// }
// }
//
// // 完整模板见 https://leetcode.cn/circle/discuss/mOr1u6/
// type fenwick []int
//
// func newFenwickTree(n int) fenwick {
// return make(fenwick, n+1) // 使用下标 1 到 n
// }
//
// // a[i] 增加 val
// // 1 <= i <= n
// // 时间复杂度 O(log n)
// func (f fenwick) update(i, val int) {
// for ; i < len(f); i += i & -i {
// f[i] += val
// }
// }
//
// // 求前缀和 a[1] + ... + a[i]
// // 1 <= i <= n
// // 时间复杂度 O(log n)
// func (f fenwick) pre(i int) (res int) {
// for ; i > 0; i &= i - 1 {
// res += f[i]
// }
// return res % mod
// }
//
// func totalBeauty(nums []int) (ans int) {
// m := slices.Max(nums)
//
// // 计算 b 的严格递增子序列的个数
// countIncreasingSubsequence := func(b []int, g int) (res int) {
// t := newFenwickTree(m / g)
// for _, x := range b {
// x /= g
// // cnt 表示以 x 结尾的严格递增子序列的个数
// cnt := t.pre(x-1) + 1 // +1 是因为 x 可以一个数组成一个子序列
// res += cnt
// t.update(x, cnt) // 更新以 x 结尾的严格递增子序列的个数
// }
// return res % mod
// }
//
// groups := make([][]int, m+1)
// for _, x := range nums {
// for _, d := range divisors[x] {
// groups[d] = append(groups[d], x)
// }
// }
//
// f := make([]int, m+1)
// for i := m; i > 0; i-- {
// f[i] = countIncreasingSubsequence(groups[i], i)
// // 倍数容斥
// for j := i * 2; j <= m; j += i {
// f[i] -= f[j]
// }
// // 注意 |f[i]| * i < mod * (m / i) * i = mod * m
// // m 个 mod * m 相加,至多为 mod * m * m,不会超过 64 位整数最大值
// ans += f[i] * i
// }
// // 保证结果非负
// return (ans%mod + mod) % mod
// }
// Accepted solution for LeetCode #3671: Sum of Beautiful Subsequences
// Auto-generated TypeScript example from go.
function exampleSolution(): void {
}
// Reference (go):
// // Accepted solution for LeetCode #3671: Sum of Beautiful Subsequences
// package main
//
// import "slices"
//
// // https://space.bilibili.com/206214
// const mod = 1_000_000_007
// const mx = 70_001
//
// var divisors [mx][]int
//
// func init() {
// // 预处理每个数的因子
// for i := 1; i < mx; i++ {
// for j := i; j < mx; j += i { // 枚举 i 的倍数 j
// divisors[j] = append(divisors[j], i) // i 是 j 的因子
// }
// }
// }
//
// // 完整模板见 https://leetcode.cn/circle/discuss/mOr1u6/
// type fenwick []int
//
// func newFenwickTree(n int) fenwick {
// return make(fenwick, n+1) // 使用下标 1 到 n
// }
//
// // a[i] 增加 val
// // 1 <= i <= n
// // 时间复杂度 O(log n)
// func (f fenwick) update(i, val int) {
// for ; i < len(f); i += i & -i {
// f[i] += val
// }
// }
//
// // 求前缀和 a[1] + ... + a[i]
// // 1 <= i <= n
// // 时间复杂度 O(log n)
// func (f fenwick) pre(i int) (res int) {
// for ; i > 0; i &= i - 1 {
// res += f[i]
// }
// return res % mod
// }
//
// func totalBeauty(nums []int) (ans int) {
// m := slices.Max(nums)
//
// // 计算 b 的严格递增子序列的个数
// countIncreasingSubsequence := func(b []int, g int) (res int) {
// t := newFenwickTree(m / g)
// for _, x := range b {
// x /= g
// // cnt 表示以 x 结尾的严格递增子序列的个数
// cnt := t.pre(x-1) + 1 // +1 是因为 x 可以一个数组成一个子序列
// res += cnt
// t.update(x, cnt) // 更新以 x 结尾的严格递增子序列的个数
// }
// return res % mod
// }
//
// groups := make([][]int, m+1)
// for _, x := range nums {
// for _, d := range divisors[x] {
// groups[d] = append(groups[d], x)
// }
// }
//
// f := make([]int, m+1)
// for i := m; i > 0; i-- {
// f[i] = countIncreasingSubsequence(groups[i], i)
// // 倍数容斥
// for j := i * 2; j <= m; j += i {
// f[i] -= f[j]
// }
// // 注意 |f[i]| * i < mod * (m / i) * i = mod * m
// // m 个 mod * m 相加,至多为 mod * m * m,不会超过 64 位整数最大值
// ans += f[i] * i
// }
// // 保证结果非负
// return (ans%mod + mod) % mod
// }
Use this to step through a reusable interview workflow for this problem.
For each of q queries, scan the entire range to compute the aggregate (sum, min, max). Each range scan takes up to O(n) for a full-array query. With q queries: O(n × q) total. Point updates are O(1) but queries dominate.
Building the tree is O(n). Each query or update traverses O(log n) nodes (tree height). For q queries: O(n + q log n) total. Space is O(4n) ≈ O(n) for the tree array. Lazy propagation adds O(1) per node for deferred updates.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.