![]() |
VOOZH | about |
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 9Input: num[] = [2, 3, 5, 4, 5]
Output: [2, 3, 6, 3, 2]
Explanation: Next smallest palindrome is 2 3 6 3 2
Table of Content
The idea is to keep adding 1 to the number and check if it becomes a palindrome. Stop when a palindrome is found.
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.
9 4 1 8 8 0 8 8 1 4 9