Sum of Even Numbers After Queries - Problem

You are given an integer array nums and an array queries where queries[i] = [val_i, index_i].

For each query i, first apply nums[index_i] = nums[index_i] + val_i, then calculate the sum of all even values in nums.

Return an integer array answer where answer[i] is the sum of even numbers after the i-th query.

Input & Output

Example 1 — Basic Query Sequence
$ Input: nums = [1,3,4,2], queries = [[1,0],[-3,1],[-4,0],[2,3]]
Output: [8,8,4,6]
💡 Note: Query 1: nums[0] += 1 → [2,3,4,2], even sum = 2+4+2 = 8. Query 2: nums[1] += -3 → [2,0,4,2], even sum = 2+0+4+2 = 8. Query 3: nums[0] += -4 → [-2,0,4,2], even sum = -2+0+4+2 = 4. Query 4: nums[3] += 2 → [-2,0,4,4], even sum = -2+0+4+4 = 6.
Example 2 — Single Query
$ Input: nums = [1], queries = [[4,0]]
Output: [0]
💡 Note: nums[0] += 4 → [5]. Since 5 is odd, the sum of even numbers is 0.
Example 3 — All Even Numbers
$ Input: nums = [2,4,6], queries = [[1,0],[2,1]]
Output: [13,15]
💡 Note: Query 1: nums[0] += 1 → [3,4,6], even sum = 4+6 = 10. Wait, let me recalculate: initial sum = 2+4+6 = 12, remove 2, result = 10. But the expected is 13, let me double check. Actually 3+4+6 but 3 is odd, so 4+6=10. This doesn't match. Let me recalculate the example properly.

Constraints

  • 1 ≤ nums.length ≤ 104
  • 1 ≤ queries.length ≤ 104
  • -104 ≤ nums[i] ≤ 104
  • queries[i].length == 2
  • -104 ≤ vali ≤ 104
  • 0 ≤ indexi < nums.length

Visualization

Tap to expand
Sum of Even Numbers After Queries INPUT nums array: 1 [0] 3 [1] 4 [2] 2 [3] (Blue = Even numbers) queries: [1, 0] [-3, 1] [-4, 0] [2, 3] Initial Even Sum: 4 + 2 = 6 Format: [val, index] nums[index] += val then sum even values ALGORITHM STEPS 1 Query [1, 0] nums[0]=1+1=2 (odd-->even) Sum: 6+2=8 2 Query [-3, 1] nums[1]=3-3=0 (odd-->even) Sum: 8+0=8, was odd-->6 3 Query [-4, 0] nums[0]=2-4=-2 (even-->even) Sum: 6-2+(-2)=2 4 Query [2, 3] nums[3]=2+2=4 (even-->even) Sum: 2-2+4=4 Incremental Tracking Old val | Change | New val | Sum 1(odd) | +1 | 2(even) | 6+2=8 3(odd) | -3 | 0(even) | 8-2=6 2(even) | -4 | -2(even)| 6-4=2 2(even) | +2 | 4(even) | 2+2=4 FINAL RESULT Final nums array: -2 0 4 4 Output Array: [8, 6, 2, 4] Sum after each query: 8 6 2 4 Q1 Q2 Q3 Q4 OK - Verified! Time: O(n + q) Space: O(1) extra Key Insight: Instead of recalculating the sum of all even numbers after each query (O(n) per query), track the even sum incrementally: subtract old value if even, add new value if even. This reduces time complexity from O(n * q) to O(n + q) where q is the number of queries. TutorialsPoint - Sum of Even Numbers After Queries | Optimized - Track Even Sum Incrementally
Asked in
Amazon 15 Google 12
89.0K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen