MediumNo. 0985
Sum of Even Numbers After Queries — LeetCode 985 Python Solution
- Topics
- Array, Simulation
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
- Time
- O(n + m)where n and m are the lengths of the arrays nums and queries, respectively
- Space · auxiliary
- O(1)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0495 | Teemo Attacking | Easy |
| 1389 | Create Target Array in the Given Order | Easy |
| 1409 | Queries on a Permutation With Key | Medium |
| 1503 | Last Moment Before All Ants Fall Out of a Plank | Medium |
| 1535 | Find the Winner of an Array Game | Medium |
| 1560 | Most Visited Sector in a Circular Track | Easy |
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.