17. Next Smallest Palindrome
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
To solve this problem I use some constructive algo approach, which consists of the following steps.
Create a copy vector out
from the given num
array for the output.
Iterate through the first half of the out
array and make it a palindrome by mirroring values.
Compare out
with the num
array to determine if out
is greater than num
.
If out
is greater than num
, no further operation is needed, and we return out
.
If out
is not greater than num
, find the middle indices of the out
array.
To get just greater values, Increment the numbers from the middle
indices towards the corners
until a non-9 digit is encountered.
If any non-9 digit occurs then just increase it by 1and return out
.
If in out array all digits are 9, convert the array to [1, 0, 0, ..., 0, 1]
form.
Consider the input array: [1, 2, 3, 4, 5]
Time Complexity: The time complexity is primarily determined by iterating over the out array and the num array, which both have n
elements. So, the time complexity is O(n)
.
Auxiliary Space Complexity: The additional space used is for the out
array, which has the same size as the input array. Hence, the auxiliary space complexity is O(n)
.
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.