Taro Logo

Good Subsequence Queries

Hard
Asked by:
Infosys
0 views
Topics:
Arrays

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] = [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 term gcd(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 * 104
  • 1 <= nums[i] <= 5 * 104
  • 1 <= queries.length <= 5 * 104
  • queries[i] = [indi, vali]
  • 1 <= vali, p <= 5 * 104
  • 0 <= indi <= n - 1

Solution


Clarifying Questions

When 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:

  1. What are the exact criteria that define a "good subsequence" in terms of mathematical properties, frequencies, or relational constraints?
  2. What is the format of the queries, and can you provide an example of what each query asks for?
  3. What should be returned or outputted if a query has no valid good subsequence that meets the conditions?
  4. Are duplicates allowed in the input sequence, and if so, do identical values at different indices count as distinct elements when forming subsequences?
  5. Can the sequence contain negative numbers, zeros, or empty inputs?

Brute Force Solution

Approach

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:

  1. Initialize a segment tree to maintain the greatest common divisor of all elements in nums that are divisible by p.
  2. Track the total number of elements that are divisible by p.
  3. For each update query, update the value in nums, the count of multiples of p, and the corresponding position in the segment tree.
  4. Check if the overall greatest common divisor of the multiples of p is equal to p.
  5. If the number of multiples is strictly less than the total length of the array, a valid good subsequence is guaranteed to exist.
  6. If all elements in the array are multiples of p, check whether removing any single element retains a greatest common divisor of p.
  7. Accumulate and return the count of queries for which a good subsequence exists.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(q * n * log(max_val)) – In the worst case where all elements remain multiples of p, each query may check dropping each element taking up to n queries of segment tree ranges. In typical cases where not all elements are multiples, each query runs in logarithmic time.
Space Complexity
O(n) – The segment tree uses an array of size proportional to the smallest power of two greater than or equal to n, requiring linear space.

Optimal Solution

Approach

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:

  1. Normalize the array by dividing each element by p if it is divisible by p, or mapping it to 0 otherwise.
  2. Build a segment tree over the normalized array to support point updates and range GCD queries.
  3. For each query, update the element in the array and the corresponding leaf in the segment tree.
  4. Check if the overall GCD of the normalized elements across the entire array is 1; if not, no subsequence can have GCD p.
  5. If the total GCD is 1, check whether omitting any single element retains a GCD of 1.
  6. Increment the result counter whenever such a proper subsequence exists, and return the total count after processing all queries.

Code Implementation

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

Big(O) Analysis

Time Complexity
O((n + q) * log(n) * log(max_val)) – Each segment tree update takes O(log n * log(max_val)) due to the height of the tree and GCD computations. Testing for a proper subsequence takes logarithmic time using prefix and suffix GCD checks, leading to an overall efficient runtime well within limits.
Space Complexity
O(n) – The segment tree requires an array of size up to 4 * n, which takes linear auxiliary space with respect to the input size.

Edge Cases

Empty or null sequence and query arrays
How to Handle:
Return an empty output array immediately since no subsequences can be formed or queried.
Minimum-sized sequence with a single element
How to Handle:
Check if the single element satisfies the query criteria directly without attempting invalid slice operations.
Maximum-sized inputs with heavy query volume
How to Handle:
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
How to Handle:
Precompute frequency maps to handle combinatorial counting of subsequences in constant time.
Sequence elements containing negative numbers and zeros
How to Handle:
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
How to Handle:
Use 64-bit integer types and modular arithmetic during intermediate frequency calculations to prevent integer overflow.
Queries where no valid good subsequence exists
How to Handle:
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
How to Handle:
Employ coordinate compression to map large sparse values into a dense range, saving both time and memory.