#985

Sum of Even Numbers After Queries

Medium
ArraySimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + m)
Space
O(1)
O(1)
💡

Intuition

Time O(n + m)Space O(1)

Instead of recalculating the sum of even numbers from scratch for each query, we can maintain a running total of the sum of even numbers. This allows us to update the sum efficiently when we modify an element.

⚙️

Algorithm

6 steps
  1. 1Step 1: Calculate the initial sum of even numbers in the nums array.
  2. 2Step 2: Initialize an empty list to store results.
  3. 3Step 3: For each query, update the specified index in the nums array.
  4. 4Step 4: Check if the updated number is even or odd and adjust the even sum accordingly.
  5. 5Step 5: Append the current even sum to the results list.
  6. 6Step 6: Return the results list.
solution.py13 lines
1# Full working Python code
2nums = [1, 2, 3, 4]
3queries = [[1, 0], [-3, 1], [-4, 0], [2, 3]]
4even_sum = sum(x for x in nums if x % 2 == 0)
5result = []
6for val, index in queries:
7    if nums[index] % 2 == 0:
8        even_sum -= nums[index]
9    nums[index] += val
10    if nums[index] % 2 == 0:
11        even_sum += nums[index]
12    result.append(even_sum)
13print(result)

Complexity note: This complexity arises because we initially compute the sum of even numbers (O(n)), and then for each query (O(m)), we perform constant time operations to update the sum.

  • 1Maintaining a running total of even sums can significantly reduce computation time.
  • 2Understanding the impact of adding or subtracting values on evenness is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.