VOOZH about

URL: https://www.geeksforgeeks.org/dsa/given-a-number-find-next-smallest-palindrome-larger-than-this-number/

⇱ Next Smallest Palindrome - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Next Smallest Palindrome

Last Updated : 10 Apr, 2026

Given a number, in the form of an array num[] of size n containing digits from 1 to 9(inclusive). Find the next smallest palindrome strictly larger than the given number.

Input: num[] = [9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2]
Output: [9, 4, 1, 8, 8, 0, 8, 8, 1, 4, 9]
Explanation: Next smallest palindrome is 9 4 1 8 8 0 8 8 1 4 9

Input: num[] = [2, 3, 5, 4, 5]
Output: [2, 3, 6, 3, 2]
Explanation: Next smallest palindrome is 2 3 6 3 2

Try All Possible Numbers

The idea is to keep adding 1 to the number and check if it becomes a palindrome. Stop when a palindrome is found.


Output
9 4 1 8 8 0 8 8 1 4 9 

Time Complexity: Worst case O(n × 10ⁿ) because many numbers may be generated before finding the next palindrome, and each palindrome check takes O(n) time.
Space Complexity: The space complexity is O(n), since the number is stored and processed as an array of digits.

Using Mirror and Carry Propagation - O(n) time and O(n) space

  • If all digits are 9, return 1 followed by zeros and ending with 1 (Example: 999 -> 1001).
  • Otherwise, Copy the left half to the right to form a palindrome.
  • If it is not greater than the original, increase the middle digit (odd length) or middle pair (even length).
  • If a carry occurs, propagate it to the left and mirror the left half again to get the next palindrome.

Output
9 4 1 8 8 0 8 8 1 4 9 
Comment