Skip to content

Commit fde3a2f

Browse files
committed
Time: 41 ms (21.59%), Space: 16.6 MB (28.21%) - LeetHub
1 parent fe2d5e7 commit fde3a2f

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution:
2+
def nearestPalindromic(self, n: str) -> str:
3+
length = len(n)
4+
num = int(n)
5+
6+
# Edge cases for very small numbers
7+
if num == 0:
8+
return "1"
9+
if num == 1:
10+
return "0"
11+
12+
# Handle corner cases like "1000", "999"
13+
candidates = set()
14+
candidates.add(str(10**(length - 1) - 1)) # largest number with one less digit (e.g., 999 for 1000)
15+
candidates.add(str(10**length + 1)) # smallest number with one more digit (e.g., 10001 for 9999)
16+
17+
# Generate the palindrome by mirroring
18+
prefix = int(n[:(length + 1) // 2])
19+
for i in [-1, 0, 1]:
20+
new_prefix = str(prefix + i)
21+
if length % 2 == 0:
22+
candidate = new_prefix + new_prefix[::-1]
23+
else:
24+
candidate = new_prefix + new_prefix[:-1][::-1]
25+
candidates.add(candidate)
26+
27+
# Remove the original number from the candidates
28+
candidates.discard(n)
29+
30+
# Find the closest palindrome
31+
closest = min(candidates, key=lambda x: (abs(int(x) - num), int(x)))
32+
33+
return closest

0 commit comments

Comments
 (0)