Skip to content

Commit d9b2f47

Browse files
authored
Merge pull request #1021 from vivekvardhan2810/main
Find the Closest Palindrome (Leetcode) Added problem number 564
2 parents c5f5d9a + ccd1c11 commit d9b2f47

File tree

1 file changed

+134
-0
lines changed

1 file changed

+134
-0
lines changed
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
---
2+
id: find-the-closest-palindrome
3+
title: Find the Closest Palindrome
4+
sidebar_label: 564 Find the Closest Palindrome
5+
tags:
6+
- Java
7+
- string
8+
- Math
9+
description: "This document provides a solution where we need to find the nearest palindrome to a given number n, the idea is to generate potential palindromic candidates close to n and then determine which one is closest in terms of absolute difference. "
10+
---
11+
12+
## Problem
13+
14+
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**.
15+
16+
The closest is defined as the absolute difference minimized between two integers.
17+
18+
### Examples
19+
20+
**Example 1:**
21+
22+
```
23+
Input: n = "123"
24+
25+
Output: "121"
26+
27+
```
28+
29+
**Example 2:**
30+
31+
```
32+
Input: n = "1"
33+
34+
Output: "0"
35+
36+
Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0.
37+
38+
```
39+
40+
### Constraints
41+
42+
- $1 \leq n.length \leq 18$
43+
- $n$ consists of only digits.
44+
- $n$ does not have leading zeros.
45+
- $n$ is representing an integer in the range [1, $10^18$ - 1].
46+
47+
---
48+
49+
## Approach
50+
51+
To solve the problem, we need to understand the nature of the allowed moves:
52+
53+
1. **Generate Candidate Palindromes**:
54+
55+
- Generate palindromes by reflecting the first half of the number.
56+
57+
- Create palindromes by incrementing or decrementing the first half of the number.
58+
59+
- Consider edge cases such as numbers with all $9's$ or all $0's$.
60+
61+
2. **Calculate Distances**:
62+
63+
- For each candidate palindrome, compute the absolute difference from the original number $n$.
64+
65+
3. **Select the Closest Palindrome**:
66+
67+
- Among all candidates, select the one with the smallest absolute difference. In case of ties, choose the smaller number.
68+
69+
## Solution for Finding the Closest Palindrome
70+
71+
The given problem involves To find the nearest palindrome to a given number 'n', the idea is to generate potential palindromic candidates close to 'n' and then determine which one is closest in terms of absolute difference.
72+
73+
#### Code in Java
74+
75+
```java
76+
class Solution {
77+
public String nearestPalindromic(String n) {
78+
long num = Long.parseLong(n);
79+
int len = n.length();
80+
81+
// Edge cases for 1, 0, 10, 100, etc.
82+
long smaller = (long) Math.pow(10, len - 1) - 1;
83+
long larger = (long) Math.pow(10, len) + 1;
84+
85+
// Middle palindrome by modifying the first half
86+
long prefix = Long.parseLong(n.substring(0, (len + 1) / 2));
87+
long candidate1 = createPalindrome(prefix, len % 2 == 0);
88+
long candidate2 = createPalindrome(prefix - 1, len % 2 == 0);
89+
long candidate3 = createPalindrome(prefix + 1, len % 2 == 0);
90+
91+
// Collecting all candidates
92+
long[] candidates = {smaller, larger, candidate1, candidate2, candidate3};
93+
94+
// Finding the nearest palindrome
95+
long nearest = -1;
96+
for (long candidate : candidates) {
97+
if (candidate != num) {
98+
if (nearest == -1 || Math.abs(candidate - num) < Math.abs(nearest - num) ||
99+
(Math.abs(candidate - num) == Math.abs(nearest - num) && candidate < nearest)) {
100+
nearest = candidate;
101+
}
102+
}
103+
}
104+
105+
return String.valueOf(nearest);
106+
}
107+
108+
private long createPalindrome(long prefix, boolean isEvenLength) {
109+
String strPrefix = String.valueOf(prefix);
110+
StringBuilder sb = new StringBuilder(strPrefix);
111+
if (!isEvenLength) {
112+
sb.setLength(sb.length() - 1);
113+
}
114+
return Long.parseLong(strPrefix + sb.reverse().toString());
115+
}
116+
}
117+
118+
```
119+
120+
### Complexity Analysis
121+
122+
#### Time Complexity: $O(log(n))$
123+
124+
> **Reason**: Time Complexity is $O(log(n))$, Comparing a constant number of candidates (5 in this case) involves checking their absolute differences with the original number.
125+
126+
#### Space Complexity: $O(1)$
127+
128+
> **Reason**: $O(1)$ additional space, excluding the space required to store the input and output since we only use a fixed number of variables.
129+
130+
# References
131+
132+
- **LeetCode Problem:** [Find the Closest Palindrome](https://leetcode.com/problems/find-the-closest-palindrome/description/)
133+
- **Solution Link:** [Find the Closest Palindrome Solution on LeetCode](https://leetcode.com/problems/find-the-closest-palindrome/solutions/)
134+
- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/vivekvardhan43862/)

0 commit comments

Comments
 (0)