Handling Sum Queries After Update - Problem

You are given two 0-indexed arrays nums1 and nums2 and a 2D array queries of queries. There are three types of queries:

Type 1: queries[i] = [1, l, r]. Flip the values from 0 to 1 and from 1 to 0 in nums1 from index l to index r (both inclusive).

Type 2: queries[i] = [2, p, 0]. For every index 0 <= i < n, set nums2[i] = nums2[i] + nums1[i] * p.

Type 3: queries[i] = [3, 0, 0]. Find the sum of all elements in nums2.

Return an array containing all the answers to the third type queries.

Input & Output

Example 1 — Basic Operations
$ Input: nums1 = [1,0,1], nums2 = [0,0,0], queries = [[1,1,1],[2,1,0],[3,0,0]]
Output: [3]
💡 Note: Query [1,1,1]: flip nums1[1] from 0→1, so nums1=[1,1,1]. Query [2,1,0]: add nums1[i]*1 to nums2[i], so nums2=[1,1,1]. Query [3,0,0]: sum of nums2 = 1+1+1 = 3.
Example 2 — Multiple Sum Queries
$ Input: nums1 = [1,0,1,0], nums2 = [1,2,3,4], queries = [[3,0,0],[2,3,0],[3,0,0],[1,0,3],[3,0,0]]
Output: [10,16,13]
💡 Note: Initial sum=10. After [2,3,0]: add 2*3=6, sum=16. After [1,0,3]: flip all bits, nums1=[0,1,0,1], nums2 unchanged, sum=16. But wait - we need to track changes properly.
Example 3 — Range Flip Edge Case
$ Input: nums1 = [1], nums2 = [5], queries = [[2,2,0],[3,0,0],[1,0,0],[2,3,0],[3,0,0]]
Output: [7,7]
💡 Note: [2,2,0]: nums2[0] += 1*2 = 7. [3,0,0]: sum=7. [1,0,0]: flip nums1[0] to 0. [2,3,0]: add 0*3=0. [3,0,0]: sum=7.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 105
  • 0 ≤ nums1[i] ≤ 1
  • 1 ≤ nums2[i] ≤ 109
  • 1 ≤ queries.length ≤ 105
  • queries[i].length == 3
  • 1 ≤ queries[i][0] ≤ 3
  • For queries of type 1: 0 ≤ l ≤ r < nums1.length
  • For queries of type 2: 1 ≤ p ≤ 106

Visualization

Tap to expand
Sum Queries After Update: Three Operation Typesnums1 (binary):101nums2 (values):000Type 1: [1,l,r]Flip bits l to rType 2: [2,p,0]nums2[i]+=nums1[i]*pType 3: [3,0,0]Sum nums2Example: queries = [[1,1,1],[2,1,0],[3,0,0]]1. Flip index 1: [1,1,1]2. Add to nums2: [1,1,1]3. Sum nums2: 3Output: [3]
Understanding the Visualization
1
Input Arrays
nums1 (binary), nums2 (integers), queries
2
Query Processing
Type 1: flip bits, Type 2: bulk update, Type 3: sum
3
Output
Array of sums from type 3 queries
Key Takeaway
🎯 Key Insight: Track the count of 1s in nums1 instead of processing individual elements for type 2 queries
Asked in
Google 8 Amazon 5 Microsoft 3
12.8K Views
Medium Frequency
~35 min Avg. Time
485 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