17. Next Smallest Palindrome
The problem can be found at the following link: Question Link
My Approach
To solve this problem I use some constructive algo approach, which consists of the following steps.
Create a copy vector
out
from the givennum
array for the output.Iterate through the first half of the
out
array and make it a palindrome by mirroring values.Compare
out
with thenum
array to determine ifout
is greater thannum
.If
out
is greater thannum
, no further operation is needed, and we returnout
.If
out
is not greater thannum
, find the middle indices of theout
array.To get just greater values, Increment the numbers from the
middle
indices towards thecorners
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.
Explanation with Example
Consider the input array: [1, 2, 3, 4, 5]
Time and Auxiliary Space Complexity
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 isO(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 isO(n)
.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. 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 getlost01/gfg-potd repository.
Last updated