- 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
- 86 lines of C++ from the credited upstream file 2983.cpp.
- The implementation visibly relies on sequence storage.
- 4 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<bool> canMakePalindromeQueries(string s,4 vector<vector<int>>& queries) {5 const int n = s.length();6 7 8 const vector<int> mirroredDiffs = getMirroredDiffs(s);9 10 const vector<vector<int>> counts = getCounts(s);11 vector<bool> ans;12 13 for (const vector<int>& query : queries) {14 15 16 17 const int a = query[0];18 const int b = query[1] + 1;19 const int c = query[2];20 const int d = query[3] + 1;21 const int ra = n - a; 22 const int rb = n - b; 23 const int rc = n - c; 24 const int rd = n - d; 25 26 if (min(a, rd) > 0 && mirroredDiffs[min(a, rd)] > 0 ||27 n / 2 > max(b, rc) &&28 mirroredDiffs[n / 2] - mirroredDiffs[max(b, rc)] > 0 ||29 rd > b && mirroredDiffs[rd] - mirroredDiffs[b] > 0 ||30 a > rc && mirroredDiffs[a] - mirroredDiffs[rc] > 0) {31 ans.push_back(false);32 } else {33 34 35 36 vector<int> leftRangeCount = subtractArrays(counts[b], counts[a]);37 vector<int> rightRangeCount = subtractArrays(counts[d], counts[c]);38 if (a > rd)39 rightRangeCount = subtractArrays(40 rightRangeCount, subtractArrays(counts[min(a, rc)], counts[rd]));41 if (rc > b)42 rightRangeCount = subtractArrays(43 rightRangeCount, subtractArrays(counts[rc], counts[max(b, rd)]));44 if (c > rb)45 leftRangeCount = subtractArrays(46 leftRangeCount, subtractArrays(counts[min(c, ra)], counts[rb]));47 if (ra > d)48 leftRangeCount = subtractArrays(49 leftRangeCount, subtractArrays(counts[ra], counts[max(d, rb)]));50 ans.push_back(ranges::all_of(leftRangeCount, [](int freq) {51 return freq >= 0;52 }) && ranges::all_of(rightRangeCount, [](int freq) {53 return freq >= 0;54 }) && leftRangeCount == rightRangeCount);55 }56 }57 58 return ans;59 }60 61 private:62 vector<int> getMirroredDiffs(const string& s) {63 vector<int> diffs(1);64 for (int i = 0, j = s.length() - 1; i < j; ++i, --j)65 diffs.push_back(diffs.back() + (s[i] != s[j] ? 1 : 0));66 return diffs;67 }68 69 vector<vector<int>> getCounts(const string& s) {70 vector<int> count(26);71 vector<vector<int>> counts{count};72 for (const char c : s) {73 ++count[c - 'a'];74 counts.push_back(count);75 }76 return counts;77 }78 79 vector<int> subtractArrays(const vector<int>& a, const vector<int>& b) {80 vector<int> res;81 for (int i = 0; i < a.size(); ++i)82 res.push_back(a[i] - b[i]);83 return res;84 }85};86