KatInterview

564. Find the Closest Palindrome

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the closest palindromic integer to a given integer n, excluding n itself. The 'closest' is defined by the minimum absolute difference. If there's a tie in difference, we should return the smaller palindrome. The input n is given as a string and can be up to 18 digits long, which means it can be as large as 10^18 - 1. A brute-force approach of checking every number around n is too slow due to the large search space.

Solution

Find the Closest Palindrome in Python

class Solution:
    def nearestPalindromic(self, n: str) -> str:
        l = len(n)
        n_val = int(n)
        candidates = set()

        # Candidate 1: Smallest palindrome of length l+1 (e.g., 101 for n=99)
        candidates.add(10**l + 1)
        # Candidate 2: Largest palindrome of length l-1 (e.g., 99 for n=100)
        if l > 1:
            candidates.add(10**(l - 1) - 1)
        else:
            candidates.add(0) # Special case for single-digit numbers

        # Candidates based on the first half of n
        prefix_str = n[:(l + 1) // 2]
        prefix = int(prefix_str)

        for p in range(prefix - 1, prefix + 2):
            if p < 0: continue
            p_str = str(p)
            
            # Construct palindrome based on original length's parity
            if l % 2 == 1: # Odd length
                candidate_str = p_str + p_str[:-1][::-1]
            else: # Even length
                candidate_str = p_str + p_str[::-1]
            
            candidates.add(int(candidate_str))

        # Remove n itself from candidates
        if n_val in candidates:
            candidates.remove(n_val)

        # Find the best candidate
        min_diff = float('inf')
        result = -1

        for cand in sorted(list(candidates)):
            diff = abs(cand - n_val)
            if diff < min_diff:
                min_diff = diff
                result = cand
            # Since we iterate through sorted candidates, the first one found in a tie will be the smallest.
        
        return str(result)

Find the Closest Palindrome in Java

import java.util.Set;
import java.util.TreeSet;

class Solution {
    public String nearestPalindromic(String n) {
        int len = n.length();
        long nVal = Long.parseLong(n);
        
        // Use a TreeSet to store candidates, which keeps them sorted and unique.
        Set<Long> candidates = new TreeSet<>();

        // Candidate 1: Smallest palindrome of length len+1 (e.g., 101 for n=99)
        candidates.add((long) Math.pow(10, len) + 1);
        
        // Candidate 2: Largest palindrome of length len-1 (e.g., 99 for n=100)
        if (len > 1) {
            candidates.add((long) Math.pow(10, len - 1) - 1);
        } else {
            candidates.add(0L);
        }

        // Candidates based on the first half of n
        long prefix = Long.parseLong(n.substring(0, (len + 1) / 2));

        // Iterate through {prefix-1, prefix, prefix+1} to generate candidates
        for (long p = prefix - 1; p <= prefix + 1; p++) {
            if (p < 0) continue;
            String pStr = String.valueOf(p);
            StringBuilder sb = new StringBuilder(pStr);
            String reversedP = sb.reverse().toString();

            String candidateStr;
            if (len % 2 != 0) { // odd length
                candidateStr = pStr + reversedP.substring(1);
            } else { // even length
                candidateStr = pStr + reversedP;
            }
            candidates.add(Long.parseLong(candidateStr));
        }
        
        // Remove n itself from the candidates
        candidates.remove(nVal);
        
        long minDiff = -1;
        long result = -1;

        // Find the best candidate
        for (long cand : candidates) {
            long diff = Math.abs(nVal - cand);
            if (result == -1 || diff < minDiff) {
                minDiff = diff;
                result = cand;
            } else if (diff == minDiff) {
                // For ties, the smaller palindrome is chosen.
                // Since TreeSet iterates in sorted order, the first one found is the answer.
            }
        }
        
        return String.valueOf(result);
    }
}

Find the Closest Palindrome in C++

class Solution {
public:
    string nearestPalindromic(string n) {
        long len = n.length();
        long long n_val = stoll(n);

        // Use a set to store candidates and handle duplicates automatically.
        // The set also keeps them sorted, which helps in tie-breaking.
        set<long long> candidates;

        // Candidate 1: Smallest palindrome of length len+1 (e.g., 101 for n=99)
        candidates.insert((long long)pow(10, len) + 1);

        // Candidate 2: Largest palindrome of length len-1 (e.g., 99 for n=100)
        // pow(10, 0) - 1 = 0, which is correct for single-digit n.
        if (len > 1) {
            candidates.insert((long long)pow(10, len - 1) - 1);
        } else {
            candidates.insert(0);
        }

        // Candidates based on the first half of n
        long long prefix = stoll(n.substr(0, (len + 1) / 2));

        // Iterate through {prefix-1, prefix, prefix+1} to generate candidates
        for (long long p = prefix - 1; p <= prefix + 1; ++p) {
            if (p < 0) continue; // Prefix cannot be negative
            string p_str = to_string(p);
            string temp = p_str;
            reverse(temp.begin(), temp.end());
            
            string candidate_str;
            // Construct the palindrome based on original length's parity
            if (len % 2 != 0) { // odd length
                candidate_str = p_str + temp.substr(1);
            } else { // even length
                candidate_str = p_str + temp;
            }
            candidates.insert(stoll(candidate_str));
        }

        // Remove n itself from the candidates
        candidates.erase(n_val);

        long long min_diff = -1;
        long long result = -1;

        // Find the best candidate
        for (long long cand : candidates) {
            long long diff = abs(n_val - cand);
            if (result == -1 || diff < min_diff) {
                min_diff = diff;
                result = cand;
            } else if (diff == min_diff) {
                // For ties, the smaller palindrome is chosen. Since set is sorted,
                // the first one we encounter will be the smallest.
                // We don't need to do `result = min(result, cand)` because
                // we iterate through the sorted set in increasing order.
            }
        }
        
        return to_string(result);
    }
};

Find the Closest Palindrome in TypeScript

function nearestPalindromic(n: string): string {
    const len = n.length;
    const nVal = BigInt(n);

    // Use a Set to store candidates and handle duplicates automatically.
    const candidates = new Set<bigint>();

    // Candidate 1: Smallest palindrome of length len+1
    candidates.add(BigInt(10) ** BigInt(len) + BigInt(1));

    // Candidate 2: Largest palindrome of length len-1
    if (len > 1) {
        candidates.add(BigInt(10) ** BigInt(len - 1) - BigInt(1));
    } else {
        candidates.add(BigInt(0));
    }

    // Candidates based on the first half of n
    const prefixStr = n.substring(0, Math.floor((len + 1) / 2));
    const prefix = BigInt(prefixStr);

    for (let i = -1; i <= 1; i++) {
        const p = prefix + BigInt(i);
        if (p < 0) continue;

        const pStr = p.toString();
        let reversedP = pStr.split('').reverse().join('');

        let candidateStr: string;
        if (len % 2 !== 0) { // odd length
            candidateStr = pStr + reversedP.substring(1);
        } else { // even length
            candidateStr = pStr + reversedP;
        }
        candidates.add(BigInt(candidateStr));
    }

    // Remove n itself from the candidates
    candidates.delete(nVal);

    let minDiff = BigInt(-1);
    let result = BigInt(-1);

    // Find the best candidate by iterating through sorted candidates
    const sortedCandidates = Array.from(candidates).sort((a, b) => {
        if (a < b) return -1;
        if (a > b) return 1;
        return 0;
    });

    for (const cand of sortedCandidates) {
        const diff = cand > nVal ? cand - nVal : nVal - cand;
        
        if (result === BigInt(-1) || diff < minDiff) {
            minDiff = diff;
            result = cand;
        }
    }

    return result.toString();
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.