Given an integer num, the task is to find the closest Palindrome number whose absolute difference with the given number is minimal. If 2 Palindrome numbers have the same absolute difference as the given number, take the smaller one.
Examples:
Input: num = 9
Output: 9
Explanation: 9 itself is a palindrome number.Input: num = 489
Output: 484
Explanation: Closest palindrome numbers from 489 are 484 and 494. Since both have the same absolute difference, we return the smaller one, which is 484.Input: num = 1234
Output: 1221
Explanation: Closest palindrome numbers from 1234 are 1221 and 1331. Since 1221 is closer than 1331, we return 1221.
Table of Content
[Brute Force Approach] Iterate Backwards - O(n * d) Time and O(d) Space
The idea is to find the nearest palindrome by checking both smaller and larger numbers. We decrement from the given number to find the largest smaller palindrome and increment to find the smallest larger palindrome. The closest one is returned based on the absolute difference.
// C++ Program to find the closest Palindrome
// number
#include <bits/stdc++.h>
using namespace std;
// function check Palindrome
bool isPalindrome(string n)
{
for (int i = 0; i < n.size() / 2; i++)
if (n[i] != n[n.size() - 1 - i])
return false;
return true;
}
// convert number into String
string convertNumIntoString(int num)
{
// base case:
if (num == 0)
return "0";
string Snum = "";
while (num > 0) {
Snum += (num % 10 - '0');
num /= 10;
}
return Snum;
}
// function return closest Palindrome number
int closestPalindrome(int num)
{
// case1 : largest palindrome number
// which is equal to given number
int RPNum = num;
while (!isPalindrome(convertNumIntoString(abs(RPNum))))
RPNum--;
// Case 2 : smallest palindrome number
// which is greater than given number
int SPNum = num + 1;
while (!isPalindrome(convertNumIntoString(SPNum)))
SPNum++;
// check absolute difference
if (abs(num - RPNum) > abs(num - SPNum))
return SPNum;
else
return RPNum;
}
// Driver program to test above function
int main()
{
int num = 489;
cout << closestPalindrome(num) << endl;
return 0;
}
// Java program to find the closest
// Palindrome number
import java.io.*;
class GFG {
// Function to check Palindrome
public static boolean isPalindrome(String s)
{
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
// Function return closest Palindrome number
public static void closestPalindrome(int num)
{
// Case1 : largest palindrome number
// which is equal to given number
int RPNum = num;
while (isPalindrome(Integer.toString(RPNum))
== false) {
RPNum--;
}
// Case 2 : smallest palindrome number
// which is greater than given number
int SPNum = num + 1;
while (isPalindrome(Integer.toString(SPNum))
== false) {
SPNum++;
}
// Check absolute difference
if (Math.abs(num - SPNum) < Math.abs(num - RPNum)) {
System.out.println(SPNum);
}
else
System.out.println(RPNum);
}
// Driver code
public static void main(String[] args)
{
int n = 489;
closestPalindrome(n);
}
}
# Python3 program to find the
# closest Palindrome number
# Function to check Palindrome
def isPalindrome(n):
for i in range(len(n) // 2):
if (n[i] != n[-1 - i]):
return False
return True
# Convert number into String
def convertNumIntoString(num):
Snum = str(num)
return Snum
# Function return closest Palindrome number
def closestPalindrome(num):
# Case1 : largest palindrome number
# which is equal to given number
RPNum = num
while (not isPalindrome(
convertNumIntoString(abs(RPNum)))):
RPNum -= 1
# Case2 : smallest palindrome number
# which is greater than given number
SPNum = num + 1
while (not isPalindrome(
convertNumIntoString(SPNum))):
SPNum += 1
# Check absolute difference
if (abs(num - RPNum) > abs(num - SPNum)):
return SPNum
else:
return RPNum
# Driver Code
if __name__ == '__main__':
num = 489
print(closestPalindrome(num))
// C# program to find the closest
// Palindrome number
using System;
class GFG {
// Function to check Palindrome
public static bool isPalindrome(string s)
{
int left = 0;
int right = s.Length - 1;
while (left < right) {
if (s[left] != s[right]) {
return false;
}
left++;
right--;
}
return true;
}
// Function return closest Palindrome number
public static void closestPalindrome(int num)
{
// Case1 : largest palindrome number
// which is equal to given number
int RPNum = num;
while (isPalindrome(RPNum.ToString()) == false) {
RPNum--;
}
// Case 2 : smallest palindrome number
// which is greater than given number
int SPNum = num + 1;
while (isPalindrome(SPNum.ToString()) == false) {
SPNum++;
}
// Check absolute difference
if (Math.Abs(num - SPNum) < Math.Abs(num - RPNum)) {
Console.WriteLine(SPNum);
}
else
Console.WriteLine(RPNum);
}
// Driver code
public static void Main(string[] args)
{
int num = 489;
closestPalindrome(num);
}
}
// JavaScript Program to find the closest Palindrome
// number
// function check Palindrome
function isPalindrome(n)
{
for (let i = 0; i < Math.floor(n.length / 2); i++)
if (n[i] != n[n.length - 1 - i])
return false;
return true;
}
// convert number into String
function convertNumIntoString(num)
{
// base case:
if (num == 0)
return "0";
let Snum = num + '';
return Snum;
}
// function return closest Palindrome number
function closestPalindrome(num)
{
// case1 : largest palindrome number
// which is equal to given number
let RPNum = num;
while (!isPalindrome(convertNumIntoString(Math.abs(RPNum))))
RPNum--;
// Case 2 : smallest palindrome number
// which is greater than given number
let SPNum = num + 1;
while (!isPalindrome(convertNumIntoString(SPNum)))
SPNum++;
// check absolute difference
if (Math.abs(num - RPNum) > Math.abs(num - SPNum))
return SPNum;
else
return RPNum;
}
// Driver program to test above function
let num = 489;
console.log(closestPalindrome(num));
Output
484
Time Complexity: O(n*d), as we first iterate backward from num and then forward from num until we find a palindromic number, which can approximately run for O(n) times and for checking if its a palindrome it takes d time, where d is the number of digits in the number.
Auxiliary Space: O(d), as at every iteration we create a string to store the number.
[Expected Approach] Manipulate First Half of the Number - O(d) Time and O(d) Space
The idea is to construct three candidate palindromes by manipulating the first half of the number. First, we mirror the first half to get a direct palindrome. Then, we decrease the first half and mirror it to get a smaller palindrome. Finally, we increase the first half and mirror it to get a larger palindrome. The closest palindrome is determined by comparing the absolute differences from the original number.
Steps to implement the above idea:
- Convert the given number to a string for easy manipulation.
- Extract the first half of the number as a substring.
- Mirror this half to form a direct palindrome (Case 1).
- Decrease the first half, mirror it to get a smaller palindrome (Case 2).
- Increase the first half, mirror it to get a larger palindrome (Case 3).
- Convert all three palindrome candidates back to integers.
- Compare their absolute differences from the original number.
- Return the closest palindrome; if ties exist, return the smallest one.
// C++ implementation to find the closest
// palindrome by manipulating the
// first half of the number.
#include <bits/stdc++.h>
using namespace std;
// Function to convert an integer to a string
string tostring(int num) {
string str = "";
while (num) {
str += char(num % 10 + '0');
num /= 10;
}
reverse(str.begin(), str.end());
return str;
}
// Function to convert a string to an integer
int stoL(string str) {
int x = 0;
for (auto ch : str) {
x *= 10;
x += (ch - '0');
}
return x;
}
// Function to create a palindrome from a given half string
string makepalindrome(string halfStr, int length) {
string reversedHalf = halfStr;
reverse(reversedHalf.begin(), reversedHalf.end());
if (length % 2 == 0) {
return halfStr + reversedHalf;
} else {
halfStr.pop_back();
return halfStr + reversedHalf;
}
}
// Function to find the closest palindrome to a given number
int closestPalindrome(int num) {
if (num >= 0 && num <= 9) {
return num;
}
string number = tostring(num);
int length = number.size();
int val1, val2, val3;
string halfNumber = "";
// Extract the first half of the number
for (int i = 0; i <= (length - 1) / 2; ++i) {
halfNumber.push_back(number[i]);
}
string modifiedStr = halfNumber;
// Case 1: Keeping the same first half
modifiedStr = makepalindrome(modifiedStr, length);
val1 = stoL(modifiedStr);
modifiedStr = halfNumber;
// Case 2: Decreasing the first half
val2 = stoL(halfNumber) - 1;
modifiedStr = tostring(val2);
modifiedStr = makepalindrome(modifiedStr, length);
if (modifiedStr.size() < number.size() - 1) {
modifiedStr.push_back('9');
}
val2 = stoL(modifiedStr);
// Case 3: Increasing the first half
bool adjust = false;
val3 = stoL(halfNumber) + 1;
modifiedStr = tostring(val3);
if (modifiedStr.size() > halfNumber.size()) {
modifiedStr.pop_back();
adjust = true;
}
modifiedStr = makepalindrome(modifiedStr, length);
if (adjust && modifiedStr.size() == number.size()) {
modifiedStr.insert(modifiedStr.size() - 1, "0");
}
val3 = stoL(modifiedStr);
// Finding the closest palindrome
int diff = abs(num - val2);
int res = val2;
if (diff > abs(num - val1)) {
diff = abs(num - val1);
res = val1;
}
if (diff > abs(num - val3)) {
diff = abs(num - val3);
res = val3;
}
return res;
}
int main() {
int num = 489;
cout << closestPalindrome(num) << endl;
return 0;
}
// Java implementation to find the closest
// palindrome by manipulating the
// first half of the number.
class GfG {
// Function to convert an integer to a string
static String tostring(int num) {
String str = "";
while (num > 0) {
str += (char)(num % 10 + '0');
num /= 10;
}
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
// Function to convert a string to an integer
static int stoL(String str) {
int x = 0;
for (char ch : str.toCharArray()) {
x *= 10;
x += (ch - '0');
}
return x;
}
// Function to create a palindrome from a given half string
static String makepalindrome(String halfStr, int length) {
StringBuilder reversedHalf = new StringBuilder(halfStr);
reversedHalf.reverse();
if (length % 2 == 0) {
return halfStr + reversedHalf.toString();
} else {
return halfStr.substring(0, halfStr.length() - 1) + reversedHalf;
}
}
// Function to find the closest palindrome to a given number
static int closestPalindrome(int num) {
if (num >= 0 && num <= 9) {
return num;
}
String number = tostring(num);
int length = number.length();
int val1, val2, val3;
String halfNumber = "";
// Extract the first half of the number
for (int i = 0; i <= (length - 1) / 2; ++i) {
halfNumber += number.charAt(i);
}
String modifiedStr = halfNumber;
// Case 1: Keeping the same first half
modifiedStr = makepalindrome(modifiedStr, length);
val1 = stoL(modifiedStr);
modifiedStr = halfNumber;
// Case 2: Decreasing the first half
val2 = stoL(halfNumber) - 1;
modifiedStr = tostring(val2);
modifiedStr = makepalindrome(modifiedStr, length);
if (modifiedStr.length() < number.length() - 1) {
modifiedStr += '9';
}
val2 = stoL(modifiedStr);
// Case 3: Increasing the first half
boolean adjust = false;
val3 = stoL(halfNumber) + 1;
modifiedStr = tostring(val3);
if (modifiedStr.length() > halfNumber.length()) {
modifiedStr = modifiedStr.substring(0, modifiedStr.length() - 1);
adjust = true;
}
modifiedStr = makepalindrome(modifiedStr, length);
if (adjust && modifiedStr.length() == number.length()) {
modifiedStr = modifiedStr.substring(0, modifiedStr.length() - 1) + "0";
}
val3 = stoL(modifiedStr);
// Finding the closest palindrome
int diff = Math.abs(num - val2);
int res = val2;
if (diff > Math.abs(num - val1)) {
diff = Math.abs(num - val1);
res = val1;
}
if (diff > Math.abs(num - val3)) {
diff = Math.abs(num - val3);
res = val3;
}
return res;
}
public static void main(String[] args) {
int num = 489;
System.out.println(closestPalindrome(num));
}
}
# Python implementation to find the closest
# palindrome by manipulating the
# first half of the number.
def tostring(num):
str_num = ""
while num > 0:
str_num += chr(num % 10 + ord('0'))
num //= 10
return str_num[::-1]
def stol(str_num):
x = 0
for ch in str_num:
x = x * 10 + (ord(ch) - ord('0'))
return x
def makepalindrome(half_str, length):
reversed_half = half_str[::-1]
if length % 2 == 0:
return half_str + reversed_half
else:
return half_str[:-1] + reversed_half
def closest_palindrome(num):
if 0 <= num <= 9:
return num
number = tostring(num)
length = len(number)
half_number = number[:(length + 1) // 2]
# Case 1: Keeping the same first half
val1 = stol(makepalindrome(half_number, length))
# Case 2: Decreasing the first half
val2 = stol(half_number) - 1
modified_str = tostring(val2)
modified_str = makepalindrome(modified_str, length)
if len(modified_str) < len(number) - 1:
modified_str += '9'
val2 = stol(modified_str)
# Case 3: Increasing the first half
adjust = False
val3 = stol(half_number) + 1
modified_str = tostring(val3)
if len(modified_str) > len(half_number):
modified_str = modified_str[:-1]
adjust = True
modified_str = makepalindrome(modified_str, length)
if adjust and len(modified_str) == len(number):
modified_str = modified_str[:-1] + "0"
val3 = stol(modified_str)
# Finding the closest palindrome
diff = abs(num - val2)
res = val2
if diff > abs(num - val1):
diff = abs(num - val1)
res = val1
if diff > abs(num - val3):
res = val3
return res
if __name__ == "__main__":
num = 489
print(closest_palindrome(num))
// C# implementation to find the closest
// palindrome by manipulating the
// first half of the number.
using System;
using System.Text;
class GfG {
// Function to convert an integer to a string
static string tostring(int num) {
string str = "";
while (num > 0) {
str += (char)(num % 10 + '0');
num /= 10;
}
StringBuilder sb = new StringBuilder(str);
char[] arr = sb.ToString().ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
// Function to convert a string to an integer
static int stoL(string str) {
int x = 0;
foreach (char ch in str) {
x *= 10;
x += (ch - '0');
}
return x;
}
// Function to create a palindrome from a given half string
static string makepalindrome(string halfStr, int length) {
char[] arr = halfStr.ToCharArray();
Array.Reverse(arr);
string reversedHalf = new string(arr);
if (length % 2 == 0) {
return halfStr + reversedHalf;
} else {
return halfStr.Substring(0, halfStr.Length - 1) + reversedHalf;
}
}
// Function to find the closest palindrome to a given number
static int closestPalindrome(int num) {
if (num >= 0 && num <= 9) {
return num;
}
string number = tostring(num);
int length = number.Length;
int val1, val2, val3;
string halfNumber = "";
// Extract the first half of the number
for (int i = 0; i <= (length - 1) / 2; ++i) {
halfNumber += number[i];
}
string modifiedStr = halfNumber;
// Case 1: Keeping the same first half
modifiedStr = makepalindrome(modifiedStr, length);
val1 = stoL(modifiedStr);
modifiedStr = halfNumber;
// Case 2: Decreasing the first half
val2 = stoL(halfNumber) - 1;
modifiedStr = tostring(val2);
modifiedStr = makepalindrome(modifiedStr, length);
if (modifiedStr.Length < number.Length - 1) {
modifiedStr += '9';
}
val2 = stoL(modifiedStr);
// Case 3: Increasing the first half
bool adjust = false;
val3 = stoL(halfNumber) + 1;
modifiedStr = tostring(val3);
if (modifiedStr.Length > halfNumber.Length) {
modifiedStr = modifiedStr.Substring(0, modifiedStr.Length - 1);
adjust = true;
}
modifiedStr = makepalindrome(modifiedStr, length);
if (adjust && modifiedStr.Length == number.Length) {
modifiedStr = modifiedStr.Substring(0, modifiedStr.Length - 1) + "0";
}
val3 = stoL(modifiedStr);
// Finding the closest palindrome
int diff = Math.Abs(num - val2);
int res = val2;
if (diff > Math.Abs(num - val1)) {
diff = Math.Abs(num - val1);
res = val1;
}
if (diff > Math.Abs(num - val3)) {
diff = Math.Abs(num - val3);
res = val3;
}
return res;
}
public static void Main() {
int num = 489;
Console.WriteLine(closestPalindrome(num));
}
}
// JavaScript implementation to find the closest
// palindrome by manipulating the
// first half of the number.
// Function to convert an integer to a string
function tostring(num) {
let str = "";
while (num > 0) {
str += String.fromCharCode((num % 10) + 48);
num = Math.floor(num / 10);
}
return str.split('').reverse().join('');
}
// Function to convert a string to an integer
function stoL(str) {
let x = 0;
for (let ch of str) {
x *= 10;
x += (ch.charCodeAt(0) - 48);
}
return x;
}
// Function to create a palindrome from a given half string
function makepalindrome(halfStr, length) {
let reversedHalf = halfStr.split('').reverse().join('');
if (length % 2 === 0) {
return halfStr + reversedHalf;
} else {
return halfStr.substring(0, halfStr.length - 1) + reversedHalf;
}
}
// Function to find the closest palindrome to a given number
function closestPalindrome(num) {
if (num >= 0 && num <= 9) {
return num;
}
let number = tostring(num);
let length = number.length;
let val1, val2, val3;
let halfNumber = "";
// Extract the first half of the number
for (let i = 0; i <= Math.floor((length - 1) / 2); ++i) {
halfNumber += number[i];
}
let modifiedStr = halfNumber;
// Case 1: Keeping the same first half
modifiedStr = makepalindrome(modifiedStr, length);
val1 = stoL(modifiedStr);
modifiedStr = halfNumber;
// Case 2: Decreasing the first half
val2 = stoL(halfNumber) - 1;
modifiedStr = tostring(val2);
modifiedStr = makepalindrome(modifiedStr, length);
if (modifiedStr.length < number.length - 1) {
modifiedStr += '9';
}
val2 = stoL(modifiedStr);
// Case 3: Increasing the first half
let adjust = false;
val3 = stoL(halfNumber) + 1;
modifiedStr = tostring(val3);
if (modifiedStr.length > halfNumber.length) {
modifiedStr = modifiedStr.substring(0, modifiedStr.length - 1);
adjust = true;
}
modifiedStr = makepalindrome(modifiedStr, length);
if (adjust && modifiedStr.length === number.length) {
modifiedStr = modifiedStr.substring(0, modifiedStr.length - 1) + "0";
}
val3 = stoL(modifiedStr);
// Finding the closest palindrome
let diff = Math.abs(num - val2);
let res = val2;
if (diff > Math.abs(num - val1)) {
diff = Math.abs(num - val1);
res = val1;
}
if (diff > Math.abs(num - val3)) {
diff = Math.abs(num - val3);
res = val3;
}
return res;
}
// Driver code
let num = 489;
console.log(closestPalindrome(num));
Output
484