Given a number N. our task is to find the closest Palindrome number whose absolute difference with given number is minimum and absolute difference must be greater than 0.
Examples:
Input : N = 121
Output : 131 or 111
Explanation: Both having equal absolute difference
with the given number.
Input : N = 1234
Output : 1221
Asked In : Amazon
Simple Solution is to find the largest palindrome number which is smaller to given number and also find the first palindrome number which is greater than Given number.we can find there Palindromic numbers by simply decreasing and increasing by one in given number until we find these palindromic numbers.
Below is the implementation of above idea :
C++
#include <bits/stdc++.h>
using namespace std;
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 ;
}
string convertNumIntoString( int num)
{
if (num == 0)
return "0" ;
string Snum = "" ;
while (num > 0) {
Snum += (num % 10 - '0' );
num /= 10;
}
return Snum;
}
int closestPalindrome( int num)
{
int RPNum = num - 1;
while (!isPalindrome(convertNumIntoString( abs (RPNum))))
RPNum--;
int SPNum = num + 1;
while (!isPalindrome(convertNumIntoString(SPNum)))
SPNum++;
if ( abs (num - RPNum) > abs (num - SPNum))
return SPNum;
else
return RPNum;
}
int main()
{
int num = 121;
cout << closestPalindrome(num) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
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 ;
}
public static void closestPalindrome( int num)
{
int RPNum = num - 1 ;
while (isPalindrome(Integer.toString(RPNum))
== false ) {
RPNum--;
}
int SPNum = num + 1 ;
while (isPalindrome(Integer.toString(SPNum))
== false ) {
SPNum++;
}
if (Math.abs(num - SPNum) < Math.abs(num - RPNum)) {
System.out.println(SPNum);
}
else
System.out.println(RPNum);
}
public static void main(String[] args)
{
int n = 121 ;
closestPalindrome(n);
}
}
|
Python3
def isPalindrome(n):
for i in range ( len (n) / / 2 ):
if (n[i] ! = n[ - 1 - i]):
return False
return True
def convertNumIntoString(num):
Snum = str (num)
return Snum
def closestPalindrome(num):
RPNum = num - 1
while ( not isPalindrome(
convertNumIntoString( abs (RPNum)))):
RPNum - = 1
SPNum = num + 1
while ( not isPalindrome(
convertNumIntoString(SPNum))):
SPNum + = 1
if ( abs (num - RPNum) > abs (num - SPNum)):
return SPNum
else :
return RPNum
if __name__ = = '__main__' :
num = 121
print (closestPalindrome(num))
|
C#
using System;
class GFG {
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 ;
}
public static void closestPalindrome( int num)
{
int RPNum = num - 1;
while (isPalindrome(RPNum.ToString()) == false ) {
RPNum--;
}
int SPNum = num + 1;
while (isPalindrome(SPNum.ToString()) == false ) {
SPNum++;
}
if (Math.Abs(num - SPNum) < Math.Abs(num - RPNum)) {
Console.WriteLine(SPNum);
}
else
Console.WriteLine(RPNum);
}
public static void Main( string [] args)
{
int n = 121;
closestPalindrome(n);
}
}
|
Javascript
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 ;
}
function convertNumIntoString(num)
{
if (num == 0)
return "0" ;
let Snum = num + '' ;
return Snum;
}
function closestPalindrome(num)
{
let RPNum = num - 1;
while (!isPalindrome(convertNumIntoString(Math.abs(RPNum))))
RPNum--;
let SPNum = num + 1;
while (!isPalindrome(convertNumIntoString(SPNum)))
SPNum++;
if (Math.abs(num - RPNum) > Math.abs(num - SPNum))
return SPNum;
else
return RPNum;
}
let num = 121;
console.log(closestPalindrome(num), "</br>" );
|
PHP
<?php
function isPalindrome( $n )
{
for ( $i = 0; $i < floor ( strlen ( $n ) / 2); $i ++)
if ( $n [ $i ] != $n [ strlen ( $n ) - 1 - $i ])
return false;
return true;
}
function convertNumIntoString( $num )
{
if ( $num == 0)
return "0" ;
$Snum = "" ;
while ( $num > 0)
{
$Snum .= ( $num % 10 - '0' );
$num =(int)( $num / 10);
}
return $Snum ;
}
function closestPalindrome( $num )
{
$RPNum = $num - 1;
while (!isPalindrome(convertNumIntoString( abs ( $RPNum ))))
$RPNum --;
$SPNum = $num + 1;
while (!isPalindrome(convertNumIntoString( $SPNum )))
$SPNum ++;
if ( abs ( $num - $RPNum ) > abs ( $num - $SPNum ))
return $SPNum ;
else
return $RPNum ;
}
$num = 121;
echo closestPalindrome( $num ). "\n" ;
?>
|
Complexity Analysis:
- The time complexity of the given algorithm is O(num*log(num)) since it loops through each digit of the input number.
- The auxiliary space of the algorithm is O(1) since it does not use any additional space that depends on the input size.
Efficient Approach: This approach is based on a little bit of mathematical understanding and logical intuition.
For any possible number, there are 5 cases:
(Say the number is 4723)
Case 1 – The next closest palindrome has one digit extra : So here it will be 10001.
Case 2 – The next closest palindrome has one digit less: So here it will be 999.
Case 3 – The next closest palindrome has the same number of digits.
For case 3 there are 3 subcases:
The middle digit remains same. Postfix is the mirror image of prefix. So here 47(prefix) – 74(postfix)–>4774.
The middle digit increases by 1. Postfix is the mirror image of prefix. So here 4884.
The middle digit decreases by 1. Postfix is the mirror image of prefix. So here 4664.
Among these 5 candidates:
The candidate having the least absolute difference from the original number is the answer. In this case it is 4774.
Overall, the program iterates over the candidate palindromic numbers and finds the one that is closest to the input number. The program uses basic mathematical operations such as finding the prefix of the input number and creating palindromic versions of numbers to achieve this.
Follow below steps to solve this problem:
- Create a vector to store candidate palindromic numbers.
- Determine the length of the input number and the middle index.
- If the input number has a length of 1, return the string of that number minus 1 as the closest palindromic number.
- Add two candidate palindromic numbers to the vector: the smallest palindromic number greater than the input number, and the largest palindromic number smaller than the input number.
- Create a vector of three numbers that have the same prefix as the input number: the prefix itself, the prefix incremented by 1, and the prefix decremented by 1.
- For each number in the prefix vector, create a palindromic number by appending its reverse to itself. If the input number has an odd length, remove the last character of the reverse before appending.
- Add each candidate palindromic number to the vector.
- Iterate over the candidate vector and find the candidate with the smallest absolute difference to the input number. If there are multiple candidates with the same absolute difference, select the smallest one.
C++14
#include <bits/stdc++.h>
using namespace std;
string closestPalindrome(string n)
{
vector< long > candidates;
int len = n.length();
int mid = (len + 1) / 2;
if (len == 1)
return to_string(stoi(n) - 1);
candidates.push_back( pow (10, len) + 1);
candidates.push_back( pow (10, len - 1) - 1);
long prefix = stol(n.substr(0, mid));
vector< long > temp = { prefix, prefix + 1, prefix - 1 };
for ( long i : temp) {
string res = to_string(i);
if (len & 1)
res.pop_back();
reverse(res.begin(), res.end());
string peep = to_string(i) + res;
candidates.push_back(stol(peep));
}
long minDiff = LONG_MAX, result, tip = stol(n);
for ( int i = 0; i < 5; i++) {
if (candidates[i] != tip
&& minDiff > abs (candidates[i] - tip)) {
result = candidates[i];
minDiff = abs (candidates[i] - tip);
}
else if ( abs (candidates[i] - tip) == minDiff)
result = min(result, candidates[i]);
}
return to_string(result);
}
int main()
{
string num = "489" ;
cout << closestPalindrome(num) << endl;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ClosestPalindrome {
public static String closestPalindrome(String n) {
List<Long> candidates = new ArrayList<>();
int length = n.length();
int mid = (length + 1 ) / 2 ;
if (length == 1 ) {
long num = Long.parseLong(n);
return String.valueOf(num - 1 );
}
candidates.add(( long ) Math.pow( 10 , length) + 1 );
candidates.add(( long ) Math.pow( 10 , length - 1 ) - 1 );
int prefix = Integer.parseInt(n.substring( 0 , mid));
List<Integer> temp = Arrays.asList(prefix, prefix + 1 , prefix - 1 );
for ( int i : temp) {
String res = String.valueOf(i);
if ((length & 1 ) != 0 ) {
res = res.substring( 0 , res.length() - 1 );
}
String peep = i + new StringBuilder(res).reverse().toString();
candidates.add(Long.parseLong(peep));
}
long minDiff = Long.MAX_VALUE;
long result = Long.parseLong(n);
long tip = Long.parseLong(n);
for ( int i = 0 ; i < 5 ; i++) {
long candidate = candidates.get(i);
if (candidate != tip && minDiff > Math.abs(candidate - tip)) {
result = candidate;
minDiff = Math.abs(candidate - tip);
} else if (Math.abs(candidate - tip) == minDiff) {
result = Math.min(result, candidate);
}
}
return String.valueOf(result);
}
public static void main(String[] args) {
String num = "489" ;
System.out.println(closestPalindrome(num));
}
}
|
Python3
def closestPalindrome(n):
candidates = []
length = len (n)
mid = (length + 1 ) / / 2
if length = = 1 :
return str ( int (n) - 1 )
candidates.append( 10 * * length + 1 )
candidates.append( 10 * * (length - 1 ) - 1 )
prefix = int (n[:mid])
temp = [prefix, prefix + 1 , prefix - 1 ]
for i in temp:
res = str (i)
if length & 1 :
res = res[: - 1 ]
peep = str (i) + res[:: - 1 ]
candidates.append( int (peep))
minDiff = float ( 'inf' )
result = tip = int (n)
for i in range ( 5 ):
if candidates[i] ! = tip and minDiff > abs (candidates[i] - tip):
result = candidates[i]
minDiff = abs (candidates[i] - tip)
elif abs (candidates[i] - tip) = = minDiff:
result = min (result, candidates[i])
return str (result)
num = "489"
print (closestPalindrome(num))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static string ClosestPalindrome( string n)
{
List< long > candidates = new List< long >();
int len = n.Length;
int mid = (len + 1) / 2;
if (len == 1)
return ( long .Parse(n) - 1).ToString();
candidates.Add(( long )Math.Pow(10, len) + 1);
candidates.Add(( long )Math.Pow(10, len - 1) - 1);
long prefix = long .Parse(n.Substring(0, mid));
List< long > temp
= new List< long >{ prefix, prefix + 1,
prefix - 1 };
foreach ( long i in temp)
{
string res = i.ToString();
if ((len & 1) == 1)
res = res.Remove(res.Length - 1);
res = new string (res.Reverse().ToArray());
string peep = i.ToString() + res;
candidates.Add( long .Parse(peep));
}
long minDiff = long .MaxValue, result = 0,
tip = long .Parse(n);
for ( int i = 0; i < 5; i++) {
if (candidates[i] != tip
&& minDiff
> Math.Abs(candidates[i] - tip)) {
result = candidates[i];
minDiff = Math.Abs(candidates[i] - tip);
}
else if (Math.Abs(candidates[i] - tip)
== minDiff) {
result = Math.Min(result, candidates[i]);
}
}
return result.ToString();
}
static void Main()
{
string num = "489" ;
Console.WriteLine(ClosestPalindrome(num));
}
}
|
Javascript
function closestPalindrome(n) {
let candidates = [];
let len = n.length;
let mid = Math.floor((len + 1) / 2);
if (len === 1)
return (parseInt(n) - 1).toString();
candidates.push(Math.pow(10, len) + 1);
candidates.push(Math.pow(10, len - 1) - 1);
let prefix = parseInt(n.substring(0, mid));
let temp = [prefix, prefix + 1, prefix - 1];
for (let i of temp) {
let res = i.toString();
if (len % 2 === 1)
res = res.slice(0, -1);
res = res.split( "" ).reverse().join( "" );
let peep = i.toString() + res;
candidates.push(parseInt(peep));
}
let minDiff = Number.MAX_SAFE_INTEGER;
let result, tip = parseInt(n);
for (let i = 0; i < 5; i++) {
if (candidates[i] !== tip && minDiff > Math.abs(candidates[i] - tip)) {
result = candidates[i];
minDiff = Math.abs(candidates[i] - tip);
} else if (Math.abs(candidates[i] - tip) === minDiff)
result = Math.min(result, candidates[i]);
}
return result.toString();
}
let num = "489" ;
console.log(closestPalindrome(num));
|
Time complexity: O(len(num))
Auxiliary space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
04 Oct, 2023
Like Article
Save Article