[LeetCode] Good Subsequence Queries

3901. Good Subsequence Queries

You are given an integer array nums of length n and an integer p.

A non-empty subsequence of nums is called good if:

  • Its length is strictly less than n.
  • The greatest common divisor (GCD) of its elements is exactly p.

You are also given a 2D integer array queries of length q, where each queries[i] = [ind_i, val_i] indicates that you should update nums[ind_i] to val_i.

After each query, determine whether there exists any good subsequence in the current array.

Return the number of queries for which a good subsequence exists.

gcd(a, b)

greatest common divisor

a

b

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

int __gcd(int x, int y) { return !y ? x : __gcd(y, x % y); }

class Solution {
public:
int countGoodSubseq(vector<int>& nums, int p, vector<vector<int>>& queries) {
unordered_map<int,int> freq;
int dup = 0, tot = 0;
auto add = [&](int x) {
tot++;
if(++freq[x] == 2) dup++;
};
auto del = [&](int x) {
tot--;
if(--freq[x] == 1) dup--;
if(freq[x] == 0) freq.erase(x);
};
for(int i = 0; i < nums.size(); i++) {
if(nums[i] % p) continue;
add(nums[i] / p);
}
auto gcds = [&](int skip = -1) {
int g = 0;
for(auto& [k,v] : freq) {
if(k == skip) continue;
g = __gcd(g,k);
if(g == 1) return true;
}
return false;
};
int res = 0, n = nums.size();
for(auto& q : queries) {
int idx = q[0], val = q[1];
if(nums[idx] % p == 0) del(nums[idx] / p);
nums[idx] = val;
if(nums[idx] % p == 0) add(nums[idx] / p);
if(gcds() == 1) {
if(tot != n) res++;
else {
if(dup >= 1) res++;
else {
if(freq.count(1)) res++;
else {
for(auto& [k,v] : freq) {
if(!gcds(k)) continue;
res++;
break;
}
}
}
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/good-subsequence-queries/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.