- 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
- 74 lines of Python from the credited upstream file 2983.py.
- The implementation visibly relies on sequence storage.
- No explicit 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 def canMakePalindromeQueries(3 self,4 s: str,5 queries: list[list[int]],6 ) -> list[bool]:7 n = len(s)8 9 10 mirroredDiffs = self._getMirroredDiffs(s)11 12 counts = self._getCounts(s)13 ans = []14 15 def subtractArrays(a: list[int], b: list[int]):16 return [x - y for x, y in zip(a, b)]17 18 for a, b, c, d in queries:19 20 21 22 b += 123 d += 124 ra = n - a 25 rb = n - b 26 rc = n - c 27 rd = n - d 28 29 if ((min(a, rd) > 0 and mirroredDiffs[min(a, rd)] > 0) or30 (n 2 > max(b, rc) and31 mirroredDiffs[n 2] - mirroredDiffs[max(b, rc)] > 0) or32 (rd > b and mirroredDiffs[rd] - mirroredDiffs[b] > 0) or33 (a > rc and mirroredDiffs[a] - mirroredDiffs[rc] > 0)):34 ans.append(False)35 else:36 37 38 39 leftRangeCount = subtractArrays(counts[b], counts[a])40 rightRangeCount = subtractArrays(counts[d], counts[c])41 if a > rd:42 rightRangeCount = subtractArrays(43 rightRangeCount, subtractArrays(counts[min(a, rc)], counts[rd]))44 if rc > b:45 rightRangeCount = subtractArrays(46 rightRangeCount, subtractArrays(counts[rc], counts[max(b, rd)]))47 if c > rb:48 leftRangeCount = subtractArrays(49 leftRangeCount, subtractArrays(counts[min(c, ra)], counts[rb]))50 if ra > d:51 leftRangeCount = subtractArrays(52 leftRangeCount, subtractArrays(counts[ra], counts[max(d, rb)]))53 ans.append(min(leftRangeCount) >= 054 and min(rightRangeCount) >= 055 and leftRangeCount == rightRangeCount)56 57 return ans58 59 def _getMirroredDiffs(self, s: str) -> list[int]:60 diffs = [0]61 for i, j in zip(range(len(s)), reversed(range(len(s)))):62 if i >= j:63 break64 diffs.append(diffs[-1] + (s[i] != s[j]))65 return diffs66 67 def _getCounts(self, s: str) -> list[list[int]]:68 count = [0] * 2669 counts = [count.copy()]70 for c in s:71 count[ord(c) - ord('a')] += 172 counts.append(count.copy())73 return counts74