Overflow in intermediate arithmetic
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one.
The closest is defined as the absolute difference minimized between two integers.
Example 1:
Input: n = "123" Output: "121"
Example 2:
Input: n = "1" Output: "0" Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0.
Constraints:
1 <= n.length <= 18n consists of only digits.n does not have leading zeros.n is representing an integer in the range [1, 1018 - 1].Problem summary: Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one. The closest is defined as the absolute difference minimized between two integers.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math
"123"
"1"
find-palindrome-with-fixed-length)next-palindrome-using-same-digits)find-the-count-of-good-integers)find-the-largest-palindrome-divisible-by-k)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #564: Find the Closest Palindrome
class Solution {
public String nearestPalindromic(String n) {
long x = Long.parseLong(n);
long ans = -1;
for (long t : get(n)) {
if (ans == -1 || Math.abs(t - x) < Math.abs(ans - x)
|| (Math.abs(t - x) == Math.abs(ans - x) && t < ans)) {
ans = t;
}
}
return Long.toString(ans);
}
private Set<Long> get(String n) {
int l = n.length();
Set<Long> res = new HashSet<>();
res.add((long) Math.pow(10, l - 1) - 1);
res.add((long) Math.pow(10, l) + 1);
long left = Long.parseLong(n.substring(0, (l + 1) / 2));
for (long i = left - 1; i <= left + 1; ++i) {
StringBuilder sb = new StringBuilder();
sb.append(i);
sb.append(new StringBuilder(i + "").reverse().substring(l & 1));
res.add(Long.parseLong(sb.toString()));
}
res.remove(Long.parseLong(n));
return res;
}
}
// Accepted solution for LeetCode #564: Find the Closest Palindrome
func nearestPalindromic(n string) string {
l := len(n)
res := []int{int(math.Pow10(l-1)) - 1, int(math.Pow10(l)) + 1}
left, _ := strconv.Atoi(n[:(l+1)/2])
for _, x := range []int{left - 1, left, left + 1} {
y := x
if l&1 == 1 {
y /= 10
}
for ; y > 0; y /= 10 {
x = x*10 + y%10
}
res = append(res, x)
}
ans := -1
x, _ := strconv.Atoi(n)
for _, t := range res {
if t != x {
if ans == -1 || abs(t-x) < abs(ans-x) || abs(t-x) == abs(ans-x) && t < ans {
ans = t
}
}
}
return strconv.Itoa(ans)
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #564: Find the Closest Palindrome
class Solution:
def nearestPalindromic(self, n: str) -> str:
x = int(n)
l = len(n)
res = {10 ** (l - 1) - 1, 10**l + 1}
left = int(n[: (l + 1) >> 1])
for i in range(left - 1, left + 2):
j = i if l % 2 == 0 else i // 10
while j:
i = i * 10 + j % 10
j //= 10
res.add(i)
res.discard(x)
ans = -1
for t in res:
if (
ans == -1
or abs(t - x) < abs(ans - x)
or (abs(t - x) == abs(ans - x) and t < ans)
):
ans = t
return str(ans)
// Accepted solution for LeetCode #564: Find the Closest Palindrome
struct Solution;
impl Solution {
fn nearest_palindromic(n: String) -> String {
let size = n.len();
let half = size / 2;
let value = n.parse::<i64>().unwrap();
let a = 10i64.pow(size as u32);
let b = 10i64.pow(size as u32 - 1);
let mut candidates = vec![a - 1, a + 1, b - 1, b + 1];
if size % 2 == 0 {
let left = n[..half].parse::<i64>().unwrap();
candidates.push(Self::combine(left - 1, false));
candidates.push(Self::combine(left, false));
candidates.push(Self::combine(left + 1, false));
} else {
let left = n[..half + 1].parse::<i64>().unwrap();
candidates.push(Self::combine(left - 1, true));
candidates.push(Self::combine(left, true));
candidates.push(Self::combine(left + 1, true));
}
let mut res = (std::i64::MAX, 0);
for x in candidates {
let diff = (value - x).abs();
if diff == 0 {
continue;
}
if (diff, x) < res {
res = (diff, x);
}
}
(res.1).to_string()
}
fn combine(left: i64, odd: bool) -> i64 {
let l = left.to_string();
l.chars()
.chain(l.chars().rev().skip(if odd { 1 } else { 0 }))
.collect::<String>()
.parse::<i64>()
.unwrap()
}
}
#[test]
fn test() {
let n = "123".to_string();
let res = "121".to_string();
assert_eq!(Solution::nearest_palindromic(n), res);
let n = "8".to_string();
let res = "7".to_string();
assert_eq!(Solution::nearest_palindromic(n), res);
let n = "10".to_string();
let res = "9".to_string();
assert_eq!(Solution::nearest_palindromic(n), res);
let n = "11".to_string();
let res = "9".to_string();
assert_eq!(Solution::nearest_palindromic(n), res);
}
// Accepted solution for LeetCode #564: Find the Closest Palindrome
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #564: Find the Closest Palindrome
// class Solution {
// public String nearestPalindromic(String n) {
// long x = Long.parseLong(n);
// long ans = -1;
// for (long t : get(n)) {
// if (ans == -1 || Math.abs(t - x) < Math.abs(ans - x)
// || (Math.abs(t - x) == Math.abs(ans - x) && t < ans)) {
// ans = t;
// }
// }
// return Long.toString(ans);
// }
//
// private Set<Long> get(String n) {
// int l = n.length();
// Set<Long> res = new HashSet<>();
// res.add((long) Math.pow(10, l - 1) - 1);
// res.add((long) Math.pow(10, l) + 1);
// long left = Long.parseLong(n.substring(0, (l + 1) / 2));
// for (long i = left - 1; i <= left + 1; ++i) {
// StringBuilder sb = new StringBuilder();
// sb.append(i);
// sb.append(new StringBuilder(i + "").reverse().substring(l & 1));
// res.add(Long.parseLong(sb.toString()));
// }
// res.remove(Long.parseLong(n));
// return res;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Simulate the process step by step — multiply n times, check each number up to n, or iterate through all possibilities. Each step is O(1), but doing it n times gives O(n). No extra space needed since we just track running state.
Math problems often have a closed-form or O(log n) solution hidden behind an O(n) simulation. Modular arithmetic, fast exponentiation (repeated squaring), GCD (Euclidean algorithm), and number theory properties can dramatically reduce complexity.
Review these before coding to avoid predictable interview regressions.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.