Here is the full interview question "Next Greater Palindrome - Uber Coding Interview | ShowOffer" from Uber on ShowOffer.io:
Problem Statement: Given a string s, find the smallest string greater than s that contains the same digits as s and is a palindrome. If no such string exists, return an empty string.
Examples:
Input: "ababa" Output: "abcba"
Input: "abaaa" Output: "acaac"
Input: "abc" Output: ""
Constraints:
Hints:
Solution: To solve this problem, you can follow these steps:
Here's a Python implementation of the solution:
`python def nextGreaterPalindrome(s: str) -> str: n = len(s) rev = s[::-1] if s == rev: half = s[:(n + 1) // 2] next_half = str(int(half) + 1) if len(next_half) > len(half) or (len(next_half) == len(half) and next_half < half): return "" return next_half[::-1] + (next_half if n % 2 == 0 else next_half[:-1])
for i in range(n - 1, -1, -1):
if s[i] < s[i - 1]:
break
if i == 0:
return ""
for j in range(n - 1, i - 1, -1):
if s[j] > s[i - 1]:
break
half = list(s[:i])
half[j], half[i - 1] = half[i - 1], half[j]
half[i:] = half[:i][::-1]
return "".join(half)
`
This solution has a time complexity of O(n) and a space complexity of O(n), where n is the length of the input string.