- 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
- 45 lines of Java from the credited upstream file 906.java.
- 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 int superpalindromesInRange(String left, String right) {3 int ans = 0;4 Long l = Long.valueOf(left);5 Long r = Long.valueOf(right);6 7 for (long i = (long) Math.sqrt(l); i * i <= r;) {8 long palindrome = nextPalindrome(i);9 long squared = palindrome * palindrome;10 if (squared <= r && isPalindrome(squared))11 ++ans;12 i = palindrome + 1;13 }14 15 return ans;16 }17 18 private long nextPalindrome(long num) {19 final String s = String.valueOf(num);20 final int n = s.length();21 22 String half = s.substring(0, (n + 1) / 2);23 String reversedHalf = new StringBuilder(half.substring(0, n / 2)).reverse().toString();24 final long candidate = Long.valueOf(half + reversedHalf);25 if (candidate >= num)26 return candidate;27 28 half = String.valueOf(Long.valueOf(half) + 1);29 reversedHalf = new StringBuilder(half.substring(0, n / 2)).reverse().toString();30 return Long.valueOf(half + reversedHalf);31 }32 33 private boolean isPalindrome(long num) {34 final String s = String.valueOf(num);35 int l = 0;36 int r = s.length() - 1;37 38 while (l < r)39 if (s.charAt(l++) != s.charAt(r--))40 return false;41 42 return true;43 }44}45