Sum of Even Numbers After Queries — LeetCode 985 Python Solution

MediumArraySimulation
Problem
#985
Reading time
3 min

The problem

You are given an integer array nums and an array queries where queries[i] = [vali, indexi]. For each query i, first, apply nums[indexi] = nums[indexi] + vali, then print the sum of the even values of nums.

Example

Input
nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
Output
[8,6,2,4]
Explanation
At the beginning, the array is [1,2,3,4].

Python solution

Python
class Solution:
    def sumEvenAfterQueries(
        self, nums: List[int], queries: List[List[int]]
    ) -> List[int]:
        s = sum(x for x in nums if x % 2 == 0)
        ans = []
        for v, i in queries:
            if nums[i] % 2 == 0:
                s -= nums[i]
            nums[i] += v
            if nums[i] % 2 == 0:
                s += nums[i]
            ans.append(s)
        return ans

Complexity

MeasureComplexity
TimeO(n + m), where n and m are the lengths of the arrays \textit{nums} and \textit{queries}, respectively
SpaceO(1) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 985. Sum of Even Numbers After Queries?
LeetCode 985. Sum of Even Numbers After Queries is rated Medium on LeetCode.
What is the time complexity of LeetCode 985. Sum of Even Numbers After Queries?
The Python solution on this page runs in O(n + m), where n and m are the lengths of the arrays \textit{nums} and \textit{queries}, respectively.
What is the space complexity of LeetCode 985. Sum of Even Numbers After Queries?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 985. Sum of Even Numbers After Queries cover?
LeetCode 985. Sum of Even Numbers After Queries is tagged Array and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview