Leetcode 1997 Solution

This article provides solution to leetcode question 1997 (next-palindrome-using-same-digits)

https://leetcode.com/problems/next-palindrome-using-same-digits

Solution

class Solution:
    def nextPalindrome(self, num: str) -> str:
        n = len(num)

        num = list(num)

        left = num[:n//2]
        mid = num[n//2:n - n//2]
        right = num[n - n//2:]

        i = len(left) - 2
        while i >= 0:
            if left[i] < left[i + 1]:
                j = len(left) - 1
                while left[i] >= left[j]:
                    j -= 1

                left[i], left[j] = left[j], left[i]

                left = left[:i + 1] + sorted(left[i + 1:])
                break
            i -= 1

        if i < 0:
            return ""

        return "".join(left + mid + list(reversed(left)))