You are given an integer array nums of length n and an integer p.
A non-empty subsequence of nums is called good if:
n.p.You are also given a 2D integer array queries of length q, where each queries[i] = [indi, vali] indicates that you should update nums[indi] to vali.
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.
The termgcd(a, b) denotes the greatest common divisor of a and b.
Example 1:
Input: nums = [4,8,12,16], p = 2, queries = [[0,3],[2,6]]
Output: 1
Explanation:
| i | [indi, vali] |
Operation | Updated nums |
Any good Subsequence |
|---|---|---|---|---|
| 0 | [0, 3] |
Update nums[0] to 3 |
[3, 8, 12, 16] |
No, as no subsequence has GCD exactly p = 2 |
| 1 | [2, 6] |
Update nums[2] to 6 |
[3, 8, 6, 16] |
Yes, subsequence [8, 6] has GCD exactly p = 2 |
Thus, the answer is 1.
Example 2:
Input: nums = [4,5,7,8], p = 3, queries = [[0,6],[1,9],[2,3]]
Output: 2
Explanation:
| i | [indi, vali] |
Operation | Updated nums |
Any good Subsequence |
|---|---|---|---|---|
| 0 | [0, 6] |
Update nums[0] to 6 |
[6, 5, 7, 8] |
No, as no subsequence has GCD exactly p = 3 |
| 1 | [1, 9] |
Update nums[1] to 9 |
[6, 9, 7, 8] |
Yes, subsequence [6, 9] has GCD exactly p = 3 |
| 2 | [2, 3] |
Update nums[2] to 3 |
[6, 9, 3, 8] |
Yes, subsequence [6, 9, 3] has GCD exactly p = 3 |
Thus, the answer is 2.
Example 3:
Input: nums = [5,7,9], p = 2, queries = [[1,4],[2,8]]
Output: 0
Explanation:
| i | [indi, vali] |
Operation | Updated nums |
Any good Subsequence |
|---|---|---|---|---|
| 0 | [1, 4] |
Update nums[1] to 4 |
[5, 4, 9] |
No, as no subsequence has GCD exactly p = 2 |
| 1 | [2, 8] |
Update nums[2] to 8 |
[5, 4, 8] |
No, as no subsequence has GCD exactly p = 2 |
Thus, the answer is 0.
Constraints:
2 <= n == nums.length <= 5 * 1041 <= nums[i] <= 5 * 1041 <= queries.length <= 5 * 104queries[i] = [indi, vali]1 <= vali, p <= 5 * 1040 <= indi <= n - 1When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
A subsequence with greatest common divisor equal to p can only contain elements that are multiples of p. If the greatest common divisor of all multiples of p equals p and not all elements of the array are used, such a subsequence is guaranteed to exist. When all elements in the entire array are multiples of p, we verify whether dropping at least one element still allows the remaining elements to achieve a greatest common divisor of p.
Here's how the algorithm would work step-by-step:
import math
from collections import defaultdict
def good_subsequence_queries(nums, p, queries):
# Count multiples of p and keep track of prefix and suffix GCDs
length = len(nums)
tree_size = 1
while tree_size < length:
tree_size *= 2
tree = [0] * (2 * tree_size)
def update(index, value):
pos = index + tree_size
tree[pos] = value if value % p == 0 else 0
pos //= 2
while pos > 0:
tree[pos] = math.gcd(tree[2 * pos], tree[2 * pos + 1])
pos //= 2
def query_gcd(left, right):
left_pos = left + tree_size
right_pos = right + tree_size
res = 0
while left_pos <= right_pos:
if left_pos % 2 == 1:
res = math.gcd(res, tree[left_pos])
left_pos += 1
if right_pos % 2 == 0:
res = math.gcd(res, tree[right_pos])
right_pos -= 1
left_pos //= 2
right_pos //= 2
return res
# Initialize the segment tree with valid multiples
count_multiples = 0
for index in range(length):
if nums[index] % p == 0:
count_multiples += 1
tree[index + tree_size] = nums[index]
else:
tree[index + tree_size] = 0
for index in range(tree_size - 1, 0, -1):
tree[index] = math.gcd(tree[2 * index], tree[2 * index + 1])
valid_queries_count = 0
# Process each query, update the tree, and test for valid subsequences
for index, new_value in queries:
old_value = nums[index]
if old_value % p == 0:
count_multiples -= 1
if new_value % p == 0:
count_multiples += 1
nums[index] = new_value
update(index, new_value)
if count_multiples == 0:
continue
total_gcd = tree[1]
if total_gcd != p:
continue
if count_multiples < length:
valid_queries_count += 1
else:
# Check if excluding any single element preserves GCD equal to p
can_form = False
for drop_idx in range(length):
left_gcd = query_gcd(0, drop_idx - 1) if drop_idx > 0 else 0
right_gcd = query_gcd(drop_idx + 1, length - 1) if drop_idx < length - 1 else 0
if math.gcd(left_gcd, right_gcd) == p:
can_form = True
break
if can_form:
valid_queries_count += 1
return valid_queries_count
A subsequence has a greatest common divisor (GCD) of p if all its elements are multiples of p and the GCD of those elements divided by p equals 1. If such a subsequence exists, taking all elements that are multiples of p (divided by p) will also have a GCD of 1, and any proper sub-selection preserving GCD 1 satisfies the condition. We maintain a segment tree of the normalized elements (divided by p if divisible, else 0) to efficiently test whether a valid proper subsequence of GCD 1 can be formed.
Here's how the algorithm would work step-by-step:
def count_good_subsequence_queries(nums: list[int], p: int, queries: list[list[int]]) -> int:
import math
size = len(nums)
# Segment tree to maintain the greatest common divisor of elements divided by p
tree = [0] * (4 * size)
def update(node: int, left: int, right: int, index: int, value: int) -> None:
if left == right:
tree[node] = value
return
mid = (left + right) // 2
if index <= mid:
update(2 * node, left, mid, index, value)
else:
update(2 * node + 1, mid + 1, right, index, value)
tree[node] = math.gcd(tree[2 * node], tree[2 * node + 1])
def query_gcd(node: int, left: int, right: int, q_left: int, q_right: int) -> int:
if q_left > right or q_right < left:
return 0
if q_left <= left and right <= q_right:
return tree[node]
mid = (left + right) // 2
left_gcd = query_gcd(2 * node, left, mid, q_left, q_right)
right_gcd = query_gcd(2 * node + 1, mid + 1, right, q_left, q_right)
return math.gcd(left_gcd, right_gcd)
# Initialize the segment tree with values divided by p if divisible, else 0
for index, val in enumerate(nums):
normalized_val = val // p if val % p == 0 else 0
update(1, 0, size - 1, index, normalized_val)
good_query_count = 0
# Process each query and check if any proper subsequence has gcd equal to 1
for query_index, query_val in queries:
nums[query_index] = query_val
normalized_val = query_val // p if query_val % p == 0 else 0
update(1, 0, size - 1, query_index, normalized_val)
total_gcd = tree[1]
if total_gcd != 1:
continue
# A proper subsequence with gcd 1 exists if the entire array can spare at least one element
prefix_gcd = query_gcd(1, 0, size - 1, 0, size - 2)
suffix_gcd = query_gcd(1, 0, size - 1, 1, size - 1)
if prefix_gcd == 1 or suffix_gcd == 1:
good_query_count += 1
else:
has_valid_subsequence = False
for drop_idx in range(size):
left_part = query_gcd(1, 0, size - 1, 0, drop_idx - 1) if drop_idx > 0 else 0
right_part = query_gcd(1, 0, size - 1, drop_idx + 1, size - 1) if drop_idx < size - 1 else 0
if math.gcd(left_part, right_part) == 1:
has_valid_subsequence = True
break
if has_valid_subsequence:
good_query_count += 1
return good_query_count
| Case | How to Handle |
|---|---|
| Empty or null sequence and query arrays | Return an empty output array immediately since no subsequences can be formed or queried. |
| Minimum-sized sequence with a single element | Check if the single element satisfies the query criteria directly without attempting invalid slice operations. |
| Maximum-sized inputs with heavy query volume | Use efficient data structures like segment trees or prefix sum frequency arrays to ensure logarithmic or near-linear query time complexity. |
| Inputs containing all identical values | Precompute frequency maps to handle combinatorial counting of subsequences in constant time. |
| Sequence elements containing negative numbers and zeros | Normalize input values or offset indices appropriately to prevent negative index out-of-bounds errors in frequency arrays. |
| Extreme boundary values exceeding standard integer limits | Use 64-bit integer types and modular arithmetic during intermediate frequency calculations to prevent integer overflow. |
| Queries where no valid good subsequence exists | Return a default fallback value such as negative one or an empty status indicator depending on the problem specification. |
| Highly skewed distributions with extreme sparsity | Employ coordinate compression to map large sparse values into a dense range, saving both time and memory. |