Skip to main content

Find the Closest Palindrome - Solution & Explanation

HardMathString13 min readAsked at: Amazon, Microsoft, Goldman Sachs +5
Practice this problem

Problem Statement

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 <= 18
  • n consists of only digits.
  • n does not have leading zeros.
  • n is representing an integer in the range [1, 1018 - 1].

Approach Overview

Problem Overview: You are given a numeric string n. Return the closest integer (not equal to n) that forms a palindrome. If two palindromes are equally close, return the smaller one.

The challenge is the size of the number. The input can exceed standard integer limits, so operations must be performed using string manipulation and careful math reasoning. The key observation: the nearest palindrome will almost always share the same prefix as the original number or a small variation of it.

Approach 1: Brute Force Search (Potentially O(k * d) time, O(1) space)

One straightforward strategy is to increment and decrement from the given number until a palindrome appears. For each candidate number, convert it to a string and check if it reads the same forward and backward. This requires repeatedly performing palindrome checks on numbers with d digits.

The issue is the search distance k can grow large before hitting a palindrome, especially for inputs like 1000...0. While each check costs O(d), the number of checks is unpredictable. This approach demonstrates the core idea but fails for large inputs because the search space can become huge.

Approach 2: Mirroring and Prefix Adjustment (O(d) time, O(d) space)

The optimal strategy builds a small set of candidate palindromes instead of searching the entire number line. Start by mirroring the left half of the number onto the right half. For example, 12345 becomes 12321. This often produces the closest palindrome directly.

However, the nearest palindrome might require adjusting the prefix. Extract the first half of the number, then generate three variations: keep the prefix unchanged, increment it by one, and decrement it by one. Mirror each version to form full palindromes. This captures cases like 12932 → 13031 or 1000 → 999.

Edge cases appear when the number length changes, such as 999 → 1001 or 1000 → 999. Handle these by also considering boundary candidates like 10^d + 1 and 10^{d-1} - 1. After generating all candidates, compute the absolute difference from the original number and choose the smallest difference, breaking ties with the smaller value.

This approach works because only a handful of palindromes can possibly be closest. Instead of scanning millions of numbers, you evaluate about five candidates. Each candidate construction and comparison takes O(d) time where d is the digit count.

Recommended for interviews: Interviewers expect the mirroring and prefix adjustment technique. Brute force shows basic reasoning about palindromes, but the optimized solution demonstrates control over string manipulation, boundary cases, and numeric reasoning. Generating candidate palindromes directly reduces the complexity to linear time relative to the digit length.

Approach 1: Mirroring and Adjustment

This approach involves mirroring the first half of the number to form the second half which can create a potential palindrome. After forming the basic mirrored palindrome, consider the numbers formed by adjusting the half upwards and downwards. This will cover all possible close numbers. Finally, choose the closest and smallest palindrome by comparing all options.

The C language solution creates a helper function to generate a mirrored palindrome given a string. It then creates potential palindrome candidates by mirroring the number, decrementing, and incrementing the middle digit(s). The closest candidate by absolute difference is selected as the solution.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n) where n is the length of the string, as it involves mirroring which is a linear operation.
Space Complexity: O(n) for storing temporary palindrome strings.

Try this approach in the editor →

Approach 2: Default Approach

Code

Python

Java

C++

Go

JavaScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Mirroring and Adjustment

Time Complexity: O(n) where n is the length of the string, as it involves mirroring which is a linear operation.
Space Complexity: O(n) for storing temporary palindrome strings.

Default Approach

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Increment/Decrement SearchO(k * d)O(1)Conceptual baseline or very small inputs where search distance is minimal
Mirroring and Prefix AdjustmentO(d)O(d)Optimal solution for large numeric strings and expected interview approach

Video Solution

Find the Closest Palindrome | Simple Observations | Leetcode 564 | codestorywithMIKcodestorywithMIK14,662 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Find the Closest Palindrome easy or hard?
Find the Closest Palindrome is classified as a Hard problem because of tricky edge cases and the need to avoid brute force. Handling digit-length transitions like 999 → 1001 or 1000 → 999 makes the implementation subtle. Once the prefix-mirroring insight is understood, the algorithm becomes manageable.
Find the Closest Palindrome Python/Java solution
Most implementations follow the same pattern across Python, Java, C++, and JavaScript. Extract the first half of the string, create mirrored candidates using prefix, prefix+1, and prefix-1, and include edge cases like 999... and 100...001. Compare absolute differences and return the closest palindrome.
How to solve Find the Closest Palindrome in O(n)?
Treat the number as a string and work with its prefix. Mirror the left half to form a palindrome, then also mirror prefix-1 and prefix+1. Add edge candidates like 10^d + 1 and 10^(d-1) - 1 to cover digit-length changes. Compare the absolute differences and pick the closest value not equal to the original number.
What is the best approach for Find the Closest Palindrome?
The most efficient approach uses mirroring and prefix adjustment. Mirror the left half of the number to create a palindrome, then also generate candidates by incrementing and decrementing the prefix. Evaluate these few candidates and choose the one with the smallest difference from the original number. This reduces the search space dramatically and runs in O(d) time where d is the number of digits.
Is Find the Closest Palindrome asked at Google/Amazon/Meta?
Palindrome and numeric string manipulation problems appear frequently in interviews at companies like Google, Amazon, and Meta. Variants of this question test understanding of edge cases, string handling, and mathematical reasoning. The optimized mirroring approach demonstrates strong problem-solving skills expected in senior interviews.
What data structure is used in Find the Closest Palindrome?
The solution primarily uses string manipulation rather than complex data structures. The number is processed as a string to safely handle very large values. Candidate palindromes are generated by modifying and mirroring string prefixes, then compared using numeric difference calculations.
What is the time complexity of Find the Closest Palindrome?
The optimal solution runs in O(d) time and O(d) space, where d is the number of digits in the input string. Only a constant number of palindrome candidates are generated by mirroring modified prefixes. Each candidate comparison and construction takes linear time with respect to the digit count.

Ready to solve this problem?

Practice Find the Closest Palindrome with our built-in code editor and test cases.

Practice on FleetCode