Sum of Even Numbers After Queries in Python

Given an array of integers A and a list of queries, we need to process each query and calculate the sum of even numbers after each modification. For the i-th query, value = queries[i][0] and index = queries[i][1], we add the value to A[index] and then find the sum of all even values in the updated array.

Problem Understanding

Let's understand with an example. If the array is [1,2,3,4] and queries are [[1,0],[-3,1],[-4,0],[2,3]]:

  • Initial array: [1,2,3,4], sum of even numbers: 2 + 4 = 6
  • Query 1: Add 1 to index 0 ? [2,2,3,4], sum: 2 + 2 + 4 = 8
  • Query 2: Add -3 to index 1 ? [2,-1,3,4], sum: 2 + 4 = 6
  • Query 3: Add -4 to index 0 ? [-2,-1,3,4], sum: -2 + 4 = 2
  • Query 4: Add 2 to index 3 ? [-2,-1,3,6], sum: -2 + 6 = 4

The result array is [8,6,2,4].

Algorithm

To solve this efficiently, we follow these steps:

  • Calculate the initial sum of all even numbers in the array
  • For each query:
    • If the current element at the target index is even, subtract it from the sum
    • Update the element by adding the query value
    • If the updated element is even, add it to the sum
    • Store the current sum in the result

Example

Here's the implementation of the solution:

class Solution:
    def sumEvenAfterQueries(self, A, queries):
        result = []
        even_sum = 0
        
        # Calculate initial sum of even numbers
        for num in A:
            if num % 2 == 0:
                even_sum += num
        
        # Process each query
        for query in queries:
            value = query[0]
            index = query[1]
            
            # If current element is even, remove it from sum
            if A[index] % 2 == 0:
                even_sum -= A[index]
            
            # Update the element
            A[index] += value
            
            # If updated element is even, add it to sum
            if A[index] % 2 == 0:
                even_sum += A[index]
            
            # Store current sum
            result.append(even_sum)
        
        return result

# Test the solution
solution = Solution()
A = [1, 2, 3, 4]
queries = [[1,0], [-3,1], [-4,0], [2,3]]
print(solution.sumEvenAfterQueries(A, queries))
[8, 6, 2, 4]

How It Works

The algorithm maintains a running sum of even numbers instead of recalculating the entire sum after each query. This optimization reduces the time complexity from O(n*q) to O(n+q), where n is the array length and q is the number of queries.

Step-by-Step Execution

def sumEvenAfterQueries(A, queries):
    result = []
    even_sum = sum(x for x in A if x % 2 == 0)
    print(f"Initial array: {A}, Initial even sum: {even_sum}")
    
    for i, (value, index) in enumerate(queries):
        print(f"\nQuery {i+1}: Add {value} to index {index}")
        
        # Remove current element if even
        if A[index] % 2 == 0:
            even_sum -= A[index]
            print(f"  Removed {A[index]} from sum, new sum: {even_sum}")
        
        # Update element
        A[index] += value
        print(f"  Updated A[{index}] = {A[index]}")
        
        # Add updated element if even
        if A[index] % 2 == 0:
            even_sum += A[index]
            print(f"  Added {A[index]} to sum, new sum: {even_sum}")
        
        result.append(even_sum)
        print(f"  Array: {A}, Even sum: {even_sum}")
    
    return result

# Test with example
A = [1, 2, 3, 4]
queries = [[1,0], [-3,1], [-4,0], [2,3]]
result = sumEvenAfterQueries(A, queries)
print(f"\nFinal result: {result}")
Initial array: [1, 2, 3, 4], Initial even sum: 6

Query 1: Add 1 to index 0
  Updated A[0] = 2
  Added 2 to sum, new sum: 8
  Array: [2, 2, 3, 4], Even sum: 8

Query 2: Add -3 to index 1
  Removed 2 from sum, new sum: 6
  Updated A[1] = -1
  Array: [2, -1, 3, 4], Even sum: 6

Query 3: Add -4 to index 0
  Removed 2 from sum, new sum: 4
  Updated A[0] = -2
  Added -2 to sum, new sum: 2
  Array: [-2, -1, 3, 4], Even sum: 2

Query 4: Add 2 to index 3
  Removed 4 from sum, new sum: -2
  Updated A[3] = 6
  Added 6 to sum, new sum: 4
  Array: [-2, -1, 3, 6], Even sum: 4

Final result: [8, 6, 2, 4]

Conclusion

This solution efficiently calculates the sum of even numbers after each query by maintaining a running sum. The key insight is to only adjust the sum when elements change their parity, avoiding the need to recalculate the entire sum for each query.

Updated on: 2026-03-25T07:20:11+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements