Super Palindromes - Problem

A super-palindrome is a positive integer that satisfies two conditions:

  • It is a palindrome (reads the same forwards and backwards)
  • It is the square of a palindrome

Given two positive integers left and right represented as strings, return the number of super-palindromes in the inclusive range [left, right].

Example: If we have a palindrome like 11, its square is 121, which is also a palindrome. Therefore, 121 is a super-palindrome.

Input & Output

Example 1 — Small Range
$ Input: left = "1", right = "10"
Output: 3
💡 Note: Super-palindromes in [1,10]: 1 (1² and both 1,1 are palindromes), 4 (2² and both 4,2 are palindromes) and 9 (3² and both 9,3 are palindromes)
Example 2 — Larger Range
$ Input: left = "1", right = "1000"
Output: 4
💡 Note: Super-palindromes: 1 (1²), 4 (2²), 9 (3²), and 121 (11²). All are palindromes and squares of palindromes.
Example 3 — High Range
$ Input: left = "100", right = "200"
Output: 1
💡 Note: Only 121 (11²) is a super-palindrome in range [100,200]. 121 is palindrome and 11 is palindrome.

Constraints

  • 1 ≤ int(left) ≤ int(right) ≤ 1018
  • left and right consist of only digits
  • left and right will not have leading zeros

Visualization

Tap to expand
Super Palindromes Generate Palindromes First Approach INPUT Range [left, right] 1 10 Numbers in Range: 1 2 3 4 5 ... Input Values: left = "1" right = "10" ALGORITHM STEPS 1 Generate Palindromes 1, 2, 3, 11, 22, 111... 2 Square Each 1^2=1, 2^2=4, 3^2=9... 3 Check if Palindrome Is square also palindrome? 4 Count in Range Check if in [left, right] Checking Process Base Square Super? 1 1 OK 2 4 OK 3 9 OK 9 is palindrome but > 10 FINAL RESULT Super Palindromes Found: 1 1^2 = 1 4 2^2 = 4 Both 1 and 4 are: - Palindromes themselves - Squares of palindromes - Within range [1, 10] Output: 2 super-palindromes count Key Insight: Instead of checking every number in range, generate palindromes and square them. A super-palindrome's root must be a palindrome with at most 5 digits (since 10^18 has 18 digits, sqrt has 9 digits max). This reduces search space from O(n) to O(sqrt(sqrt(n)))! TutorialsPoint - Super Palindromes | Generate Palindromes First Approach
Asked in
Google 15 Facebook 8
18.5K Views
Medium Frequency
~45 min Avg. Time
432 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen