Sum of Even Numbers After Queries — LeetCode 985 Python Solution
MediumArraySimulation
- Problem
- #985
- 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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n + m), where n and m are the lengths of the arrays \textit{nums} and \textit{queries}, respectively |
| Space | O(1) auxiliary |
Related problems
LeetCode 495Teemo AttackingEasyLeetCode 1389Create Target Array in the Given OrderEasyLeetCode 1409Queries on a Permutation With KeyMediumLeetCode 1503Last Moment Before All Ants Fall Out of a PlankMediumLeetCode 1535Find the Winner of an Array GameMediumLeetCode 1560Most Visited Sector in a Circular TrackEasy
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.