- 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
- 47 lines of C++ from the credited upstream file 906.cpp.
- The implementation keeps its working state in language-native values and containers.
- 2 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 int superpalindromesInRange(string left, string right) {4 int ans = 0;5 const long l = stoll(left);6 const long r = stoll(right);7 8 for (long i = sqrt(l); i * i <= r;) {9 const long palindrome = nextPalindrome(i);10 const long squared = palindrome * palindrome;11 if (squared <= r && isPalindrome(squared))12 ++ans;13 i = palindrome + 1;14 }15 16 return ans;17 }18 19 private:20 long nextPalindrome(int num) {21 const string s = to_string(num);22 const int n = s.length();23 string half = s.substr(0, (n + 1) / 2);24 string reversedHalf = reversed(half.substr(0, n / 2));25 const long candidate = stoll(half + reversedHalf);26 if (candidate >= num)27 return candidate;28 half = to_string(stoll(half) + 1);29 reversedHalf = reversed(half.substr(0, n / 2));30 return stoll(half + reversedHalf);31 }32 33 string reversed(const string& s) {34 return {s.rbegin(), s.rend()};35 }36 37 bool isPalindrome(long num) {38 const string s = to_string(num);39 int l = 0;40 int r = s.length() - 1;41 while (l < r)42 if (s[l++] != s[r--])43 return false;44 return true;45 }46};47