Problem Description
Given two positive integers left and right (as strings), count the number of integers in the inclusive range [left, right] that are super-palindromes. A super-palindrome is defined as an integer that is a palindrome and also the square of a palindrome.
Key Insights
- The range for left and right can be huge (up to 10^18), however the potential candidate palindromic roots are limited by the square root of right.
- Rather than iterating over all numbers in [left, right], generate palindromic numbers (which serve as potential roots) and then square them.
- Both odd-length and even-length palindromes need to be generated as candidate roots.
- For each candidate, square it and check if the result is a palindrome and falls within [left, right].
Space and Time Complexity
Time Complexity: O(X * log(P)) where X is the number of palindromic roots generated (bounded by roughly 10^5 candidate roots) and log(P) is the time to check if a number is a palindrome. Space Complexity: O(1) extra space (apart from the output and storage for candidate variables).
Solution
The solution generates candidate palindromic roots by constructing palindromes from half portions and then mirroring them to form full palindromes. Both odd-length and even-length fields are generated. For each candidate palindrome root, compute its square and check:
- That the square is within the range [left, right].
- That the square is itself a palindrome. The palindrome check is performed by converting the number to a string and comparing it with its reverse. This avoids iterating over the entire range [left, right] and leverages the fact that the number of palindromic roots up to sqrt(right) is small.