Find the Next Smaller Palindrome

You are provided with a number N, expressed as a string S, which is a palindrome. The task is to determine the largest number strictly less than N that is also a palindrome.

Example

Input:
T = 1
S = "12321"
Output:
"12221"

Input

The first line contains an integer T, representing the number of test cases.
For each test case, there is a single line containing the string S, which is the number for which the next smaller palindrome is to be determined.

Output

For each test case, output a single line containing the next smaller palindrome of S.

Constraints

  • 1 <= T <= 100
  • 1 <= |S| <= 10^4
  • The input string S represents a number greater than 0.

Note

  • A palindrome reads the same backward as forward; e.g., madam, racecar, 1234321.
  • Single-digit numbers are considered palindromes.
  • The resulting palindrome should not have leading zeros, except when the result is 0.
AnswerBot
4mo

Find the largest palindrome number strictly less than the given palindrome number.

  • Iterate from the middle towards the start of the number and copy the digits to the left side to create the next smalle...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Amazon

Q. Could you describe the process for designing a data structure that allows for al...read more
Q. What is Java?
Q. Given two strings s and t, return true if they are equal when both are typed int...read more
Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits