Problem Description
You are given two 0-indexed arrays, nums1 (containing only 0s and 1s) and nums2, and a list of queries. There are three types of queries:
- [1, l, r]: Flip all bits in nums1 between indices l and r (inclusive).
- [2, p, 0]: For every index i, update nums2[i] = nums2[i] + nums1[i] * p.
- [3, 0, 0]: Report the sum of all elements in nums2.
Return an array of answers corresponding to all type 3 queries.
Key Insights
- For query type 2, instead of updating every element of nums2, maintain a global sum for nums2 and update it by adding p times the number of ones in nums1.
- The challenge is effectively maintaining the count of ones in nums1 under range flip operations.
- A Segment Tree (with lazy propagation) is an ideal data structure to support efficient range-flip updates and range sum queries on nums1.
Space and Time Complexity
Time Complexity: O((n + q) * log(n)), where n is the number of elements in nums1/nums2 and q is the number of queries. Space Complexity: O(n) for the segment tree.
Solution
We maintain: • A segment tree for nums1 that supports range sum queries (to count the number of 1s) and range flip updates. The lazy propagation technique is used to efficiently flip a range by storing flip information in internal nodes. • A variable (sum2) that holds the current total sum of nums2. For a query:
- Type 1: Use the segment tree to flip bits in the range [l, r].
- Type 2: Query the segment tree for the total number of ones in nums1 and then update sum2 by adding (number_of_1s * p).
- Type 3: Append the current sum2 to the answer list.
The key trick is to avoid updating each element in nums2 individually, and instead, update the global sum directly via the count of ones in nums1.