- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 66 lines of C++ from the credited upstream file number-of-pairs-after-increment.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 8 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 vector<int> numberOfPairs(vector<int>& nums1, vector<int>& nums2, vector<vector<int>>& queries) {8 const auto& ceil_divide = [](int a, int b) {9 return (a + b - 1) / b;10 };11 12 vector<int64_t> nums(cbegin(nums2), cend(nums2));13 const auto& update = [&](unordered_map<int, int>& cnt, int left, int right, int val) {14 for (int i = left; i <= right; ++i) {15 --cnt[nums[i]];16 if (!cnt[nums[i]]) {17 cnt.erase(nums[i]);18 }19 nums[i] += val;20 ++cnt[nums[i]];21 }22 };23 24 unordered_map<int, int> cnt1;25 for (const auto& x : nums1) {26 ++cnt1[x];27 }28 const auto& B = static_cast<int>(sqrt(size(cnt1) * size(nums2))) + 1;29 vector<unordered_map<int, int>> cnt2(ceil_divide(size(nums), B));30 for (int i = 0; i < size(cnt2); ++i) {31 for (int j = i * B, bound = min((i + 1) * B, static_cast<int>(size(nums))); j < bound; ++j) {32 ++cnt2[i][nums[j]];33 }34 }35 vector<int64_t> lazy(size(cnt2));36 vector<int> result;37 for (const auto& q : queries) {38 if (q[0] == 2) {39 const auto& tot = q[1];40 int total = 0;41 for (const auto& [x, c] : cnt1) {42 for (int i = 0; i < size(cnt2); ++i) {43 if (!cnt2[i].count((tot - x) - lazy[i])) {44 continue;45 }46 total += cnt2[i][(tot - x) - lazy[i]] * c;47 }48 }49 result.emplace_back(total);50 continue;51 }52 const auto& x = q[1], &y = q[2], &val = q[3];53 if (x / B == y / B) {54 update(cnt2[x / B], x, y, val);55 continue;56 }57 update(cnt2[x / B], x, ((x / B) + 1) * B - 1, val);58 for (int i = (x / B) + 1; i < y / B; ++i) {59 lazy[i] += val;60 }61 update(cnt2[y / B], (y / B) * B, y, val);62 }63 return result;64 }65};66