Leetcode: 564. Find the Closest Palindrome
- Pattern: Search for closest number of some kind. Generate all closest palindromes and pick the optimal one: closest palindrome with less digits is "999…", with more digits "100..001" and others can be generate by summing or subtracting one from the middle digits.
- Can we break-down the problem in small and easily to solve parts? Build a palindrome with the input number by splitting it and them combining the first part in reverse order. The answer will be doing this but adding +1, +0 or -1 to the split part. Time and space complexity is \(O(n)\).
class Solution: def nearestPalindromic(self, num: str) -> str: inum = int(num) if inum <= 10: return str(inum - 1) N = len(num) c = set([int("9" * (N - 1)), int("1" + ("0" * (N - 1)) + "1")]) for e in 0, 1: for d in +1, 0, -1: p = str(int(num[:N // 2 + e]) + d) c.add(int(p[:-1] + p[::-1])) c.add(int(p + p[::-1])) ans = None for x in sorted(c): if x == inum: continue if ans is None or abs(ans - inum) > abs(x - inum): ans = x return str(ans)