- 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
- 42 lines of C++ from the credited upstream file 2564.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 3 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.
1class Solution {2 public:3 vector<vector<int>> substringXorQueries(string s,4 vector<vector<int>>& queries) {5 constexpr int kMaxBit = 30;6 vector<vector<int>> ans;7 8 unordered_map<int, pair<int, int>> valToLeftAndRight;9 10 for (int left = 0; left < s.length(); ++left) {11 int val = 0;12 if (s[left] == '0') {13 14 if (!valToLeftAndRight.contains(0))15 valToLeftAndRight[0] = {left, left};16 continue;17 }18 const int maxRight = min(static_cast<int>(s.length()), left + kMaxBit);19 for (int right = left; right < maxRight; ++right) {20 val = val * 2 + s[right] - '0';21 if (!valToLeftAndRight.contains(val))22 valToLeftAndRight[val] = {left, right};23 }24 }25 26 for (const vector<int>& query : queries) {27 const int first = query[0];28 const int second = query[1];29 const int val = first ^ second;30 const auto it = valToLeftAndRight.find(val);31 if (it == valToLeftAndRight.cend()) {32 ans.push_back({-1, -1});33 } else {34 const auto [left, right] = it->second;35 ans.push_back({left, right});36 }37 }38 39 return ans;40 }41};42