N'th palindrome of K digits
Last Updated :
13 Sep, 2023
Given two integers n and k, Find the lexicographical nth palindrome of k digits.
Examples:
Input : n = 5, k = 4
Output : 1441
Explanation:
4 digit lexicographical palindromes are:
1001, 1111, 1221, 1331, 1441
5th palindrome = 1441
Input : n = 4, k = 6
Output : 103301
Naive Approach
A brute force is to run a loop from the smallest kth digit number and check for every number whether it is palindrome or not. If it is a palindrome number then decrements the value of k. Therefore the loop runs until k becomes exhausted.
C++
// A naive approach of C++ program of finding nth
// palindrome of k digit
#include<bits/stdc++.h>
using namespace std;
// Utility function to reverse the number n
int reverseNum(int n)
{
int rem, rev=0;
while (n)
{
rem = n % 10;
rev = rev * 10 + rem;
n /= 10;
}
return rev;
}
// Boolean Function to check for palindromic
// number
bool isPalindrom(int num)
{
return num == reverseNum(num);
}
// Function for finding nth palindrome of k digits
int nthPalindrome(int n,int k)
{
// Get the smallest k digit number
int num = (int)pow(10, k-1);
while (true)
{
// check the number is palindrome or not
if (isPalindrom(num))
--n;
// if n'th palindrome found break the loop
if (!n)
break;
// Increment number for checking next palindrome
++num;
}
return num;
}
// Driver code
int main()
{
int n = 6, k = 5;
printf("%dth palindrome of %d digit = %d\n",
n, k, nthPalindrome(n, k));
n = 10, k = 6;
printf("%dth palindrome of %d digit = %d",
n, k, nthPalindrome(n, k));
return 0;
}
Java
// A naive approach of Java program of finding nth
// palindrome of k digit
import java.util.*;
class GFG
{
// Utility function to reverse the number n
static int reverseNum(int n)
{
int rem, rev = 0;
while (n > 0)
{
rem = n % 10;
rev = rev * 10 + rem;
n /= 10;
}
return rev;
}
// Boolean Function to check for palindromic
// number
static boolean isPalindrom(int num)
{
return num == reverseNum(num);
}
// Function for finding nth palindrome of k digits
static int nthPalindrome(int n, int k)
{
// Get the smallest k digit number
int num = (int)Math.pow(10, k-1);
while (true)
{
// check the number is palindrome or not
if (isPalindrom(num))
--n;
// if n'th palindrome found break the loop
if (n == 0)
break;
// Increment number for checking next palindrome
++num;
}
return num;
}
// Driver code
public static void main(String[] args)
{
int n = 6, k = 5;
System.out.println(n + "th palindrome of " + k + " digit = " + nthPalindrome(n, k));
n = 10; k = 6;
System.out.println(n + "th palindrome of " + k + " digit = " + nthPalindrome(n, k));
}
}
// This code is contributed by mits
Python3
# A naive approach of Python3 program
# of finding nth palindrome of k digit
import math;
# Utility function to
# reverse the number n
def reverseNum(n):
rev = 0;
while (n):
rem = n % 10;
rev = (rev * 10) + rem;
n = int(n / 10);
return rev;
# Boolean Function to check for
# palindromic number
def isPalindrom(num):
return num == reverseNum(num);
# Function for finding nth
# palindrome of k digits
def nthPalindrome(n, k):
# Get the smallest k digit number
num = math.pow(10, k - 1);
while (True):
# check the number is
# palindrome or not
if (isPalindrom(num)):
n-=1;
# if n'th palindrome found
# break the loop
if (not n):
break;
# Increment number for checking
# next palindrome
num+=1;
return int(num);
# Driver code
n = 6;
k = 5;
print(n,"th palindrome of",k,"digit =",nthPalindrome(n, k));
n = 10;
k = 6;
print(n,"th palindrome of",k,"digit =",nthPalindrome(n, k));
# This code is contributed by mits
C#
// A naive approach of C# program of finding nth
// palindrome of k digit
using System;
class GFG
{
// Utility function to reverse the number n
static int reverseNum(int n)
{
int rem, rev = 0;
while (n > 0)
{
rem = n % 10;
rev = rev * 10 + rem;
n /= 10;
}
return rev;
}
// Boolean Function to check for palindromic
// number
static bool isPalindrom(int num)
{
return num == reverseNum(num);
}
// Function for finding nth palindrome of k digits
static int nthPalindrome(int n, int k)
{
// Get the smallest k digit number
int num = (int)Math.Pow(10, k-1);
while (true)
{
// check the number is palindrome or not
if (isPalindrom(num))
--n;
// if n'th palindrome found break the loop
if (n == 0)
break;
// Increment number for checking next palindrome
++num;
}
return num;
}
// Driver code
public static void Main()
{
int n = 6, k = 5;
Console.WriteLine(n + "th palindrome of " + k + " digit = " + nthPalindrome(n, k));
n = 10; k = 6;
Console.WriteLine(n + "th palindrome of " + k + " digit = " + nthPalindrome(n, k));
}
}
// This code is contributed
// by Akanksha Rai
PHP
<?php
// A naive approach of PHP program
// of finding nth palindrome of k digit
// Utility function to
// reverse the number n
function reverseNum($n)
{
$rem;
$rev = 0;
while ($n)
{
$rem = $n % 10;
$rev = ($rev * 10) + $rem;
$n = (int)($n / 10);
}
return $rev;
}
// Boolean Function to check for
// palindromic number
function isPalindrom($num)
{
return $num == reverseNum($num);
}
// Function for finding nth
// palindrome of k digits
function nthPalindrome($n, $k)
{
// Get the smallest k digit number
$num = pow(10, $k - 1);
while (true)
{
// check the number is
// palindrome or not
if (isPalindrom($num))
--$n;
// if n'th palindrome found
// break the loop
if (!$n)
break;
// Increment number for checking
// next palindrome
++$num;
}
return $num;
}
// Driver code
$n = 6;
$k = 5;
echo $n, "th palindrome of ", $k, " digit = ",
nthPalindrome($n, $k), "\n";
$n = 10;
$k = 6;
echo $n,"th palindrome of ", $k, " digit = ",
nthPalindrome($n, $k), "\n";
// This code is contributed by ajit
?>
JavaScript
<script>
// A naive approach of Javascript
// program of finding nth
// palindrome of k digit
// Utility function to
// reverse the number n
function reverseNum(n)
{
let rem, rev = 0;
while (n > 0)
{
rem = n % 10;
rev = rev * 10 + rem;
n = parseInt(n / 10);
}
return rev;
}
// Boolean Function to
// check for palindromic
// number
function isPalindrom(num)
{
return num == reverseNum(num);
}
// Function for finding nth
// palindrome of k digits
function nthPalindrome(n, k)
{
// Get the smallest k digit number
let num = Math.pow(10, k-1);
while (true)
{
// check the number is
// palindrome or not
if (isPalindrom(num))
--n;
// if n'th palindrome found
// break the loop
if (n == 0)
break;
// Increment number for checking
// next palindrome
++num;
}
return num;
}
let n = 6, k = 5;
document.write(n + "th palindrome of " + k +
" digit = " + nthPalindrome(n, k) + "</br>");
n = 10; k = 6;
document.write(n + "th palindrome of " + k +
" digit = " + nthPalindrome(n, k));
</script>
Output:
6th palindrome of 5 digit = 10501
10th palindrome of 6 digit = 109901
Time complexity: O(10k)
Auxiliary space: O(1), since no extra space has been taken.
Efficient approach
An efficient method is to look for a pattern. According to the property of palindrome first, half digits are the same as the rest half digits in reverse order. Therefore, we only need to look for the first half digits as the rest of them can easily be generated. Let's take k = 8, the smallest palindrome always starts from 1 as the leading digit and goes like that for the first 4 digits of the number.
First half values for k = 8
1st: 1000
2nd: 1001
3rd: 1002
...
...
100th: 1099
So we can easily write the above sequence for nth
palindrome as: (n-1) + 1000
For k digit number, we can generalize above formula as:
If k is odd
=> num = (n-1) + 10k/2
else
=> num = (n-1) + 10k/2 - 1
Now rest half digits can be expanded by just
printing the value of num in reverse order.
But before this if k is odd then we have to truncate
the last digit of a value num
Illustration:
n = 6 k = 5
- Determine the number of first half digits = floor(5/2) = 2
- Use formula: num = (6-1) + 102 = 105
- Expand the rest half digits by reversing the value of num.
Final answer will be 10501
Below is the implementation of the above steps
C++
// C++ program of finding nth palindrome
// of k digit
#include<bits/stdc++.h>
using namespace std;
void nthPalindrome(int n, int k)
{
// Determine the first half digits
int temp = (k & 1) ? (k / 2) : (k/2 - 1);
int palindrome = (int)pow(10, temp);
palindrome += n - 1;
// Print the first half digits of palindrome
printf("%d", palindrome);
// If k is odd, truncate the last digit
if (k & 1)
palindrome /= 10;
// print the last half digits of palindrome
while (palindrome)
{
printf("%d", palindrome % 10);
palindrome /= 10;
}
printf("\n");
}
// Driver code
int main()
{
int n = 6, k = 5;
printf("%dth palindrome of %d digit = ",n ,k);
nthPalindrome(n ,k);
n = 10, k = 6;
printf("%dth palindrome of %d digit = ",n ,k);
nthPalindrome(n, k);
return 0;
}
Java
// Java program of finding nth palindrome
// of k digit
class GFG{
static void nthPalindrome(int n, int k)
{
// Determine the first half digits
int temp = (k & 1)!=0 ? (k / 2) : (k/2 - 1);
int palindrome = (int)Math.pow(10, temp);
palindrome += n - 1;
// Print the first half digits of palindrome
System.out.print(palindrome);
// If k is odd, truncate the last digit
if ((k & 1)>0)
palindrome /= 10;
// print the last half digits of palindrome
while (palindrome>0)
{
System.out.print(palindrome % 10);
palindrome /= 10;
}
System.out.println("");
}
// Driver code
public static void main(String[] args)
{
int n = 6, k = 5;
System.out.print(n+"th palindrome of "+k+" digit = ");
nthPalindrome(n ,k);
n = 10;
k = 6;
System.out.print(n+"th palindrome of "+k+" digit = ");
nthPalindrome(n, k);
}
}
// This code is contributed by mits
Python3
# Python3 program of finding nth palindrome
# of k digit
def nthPalindrome(n, k):
# Determine the first half digits
if(k & 1):
temp = k // 2
else:
temp = k // 2 - 1
palindrome = 10**temp
palindrome = palindrome + n - 1
# Print the first half digits of palindrome
print(palindrome, end="")
# If k is odd, truncate the last digit
if(k & 1):
palindrome = palindrome // 10
# print the last half digits of palindrome
while(palindrome):
print(palindrome % 10, end="")
palindrome = palindrome // 10
# Driver code
if __name__=='__main__':
n = 6
k = 5
print(n, "th palindrome of", k, " digit = ", end=" ")
nthPalindrome(n, k)
print()
n = 10
k = 6
print(n, "th palindrome of", k, "digit = ",end=" ")
nthPalindrome(n, k)
# This code is contributed by
# Sanjit_Prasad
C#
// C# program of finding nth palindrome
// of k digit
using System;
class GFG
{
static void nthPalindrome(int n, int k)
{
// Determine the first half digits
int temp = (k & 1) != 0 ? (k / 2) : (k / 2 - 1);
int palindrome = (int)Math.Pow(10, temp);
palindrome += n - 1;
// Print the first half digits
// of palindrome
Console.Write(palindrome);
// If k is odd, truncate the last digit
if ((k & 1) > 0)
palindrome /= 10;
// print the last half digits
// of palindrome
while (palindrome>0)
{
Console.Write(palindrome % 10);
palindrome /= 10;
}
Console.WriteLine("");
}
// Driver code
static public void Main ()
{
int n = 6, k = 5;
Console.Write(n+"th palindrome of " + k +
" digit = ");
nthPalindrome(n, k);
n = 10;
k = 6;
Console.Write(n+"th palindrome of " + k +
" digit = ");
nthPalindrome(n, k);
}
}
// This code is contributed by ajit
PHP
<?php
// PHP program of finding nth palindrome
// of k digit
function nthPalindrome($n, $k)
{
// Determine the first half digits
$temp = ($k & 1) ?
(int)($k / 2) : (int)($k / 2 - 1);
$palindrome = (int)pow(10, $temp);
$palindrome += $n - 1;
// Print the first half digits of palindrome
print($palindrome);
// If k is odd, truncate the last digit
if ($k & 1)
$palindrome = (int)($palindrome / 10);
// print the last half digits of palindrome
while ($palindrome > 0)
{
print($palindrome % 10);
$palindrome = (int)($palindrome / 10);
}
print("\n");
}
// Driver code
$n = 6;
$k = 5;
print($n."th palindrome of $k digit = ");
nthPalindrome($n, $k);
$n = 10;
$k = 6;
print($n."th palindrome of $k digit = ");
nthPalindrome($n, $k);
// This code is contributed by mits
?>
JavaScript
<script>
// Javascript program of finding nth palindrome of k digit
function nthPalindrome(n, k)
{
// Determine the first half digits
let temp = (k & 1) != 0 ? parseInt(k / 2, 10) : (parseInt(k / 2, 10) - 1);
let palindrome = parseInt(Math.pow(10, temp), 10);
palindrome += n - 1;
// Print the first half digits
// of palindrome
document.write(palindrome);
// If k is odd, truncate the last digit
if ((k & 1) > 0)
palindrome = parseInt(palindrome / 10, 10);
// print the last half digits
// of palindrome
while (palindrome>0)
{
document.write(palindrome % 10);
palindrome = parseInt(palindrome / 10, 10);
}
document.write("" + "</br>");
}
let n = 6, k = 5;
document.write(n+"th palindrome of " + k + " digit = ");
nthPalindrome(n, k);
n = 10;
k = 6;
document.write(n+"th palindrome of " + k + " digit = ");
nthPalindrome(n, k);
</script>
Output:
6th palindrome of 5 digit = 10501
10th palindrome of 6 digit = 109901
Time complexity: O(k)
Auxiliary space: O(1), since no extra space has been taken.
Reference:
http://stackoverflow.com/questions/11925840/how-to-calculate-nth-n-digit-palindrome-efficiently
Similar Reads
Sum of all N digit palindrome numbers
Given a number N. The task is to find the sum of all N-digit palindromes. Examples: Input: N = 2 Output: 495 Explanation: 11 + 22 + 33 + 44 + 55 + 66 + 77 + 88 + 99 = 495 Input: N = 7 Output: 49500000000 Naive Approach:Run a loop from 10^(n-1) to 10^(n) - 1 and check when the current number is palin
7 min read
Count of N-digit Palindrome numbers
Given an integer N, the task is to find the count of N-digit Palindrome numbers.Examples: Input: N = 1 Output: 9 {1, 2, 3, 4, 5, 6, 7, 8, 9} are all the possible single digit palindrome numbers.Input: N = 2 Output: 9 Approach: The first digit can be any of the 9 digits (not 0) and the last digit wil
2 min read
Check if the Sum of Digits is Palindrome or not
Given an integer n, the task is to check whether the sum of digits of n is palindrome or not.Example: Input: n = 56 Output: trueExplanation: Digit sum is (5 + 6) = 11, which is a palindrome.Input: n = 51241 Output: falseExplanation: Digit sum is (5 + 1 + 2 + 4 + 1) = 13, which is not a palindrome.Ta
9 min read
Find all palindrome numbers of given digits
Given an integer D, the task is to find all the D-digit palindrome numbers.Examples: Input: D = 1 Output: 1 2 3 4 5 6 7 8 9Input: D = 2 Output: 11 22 33 44 55 66 77 88 99 Approach: Numbers with D-digits start from 10(D - 1) to 10D - 1. So, start checking every number from this interval whether it is
5 min read
Find if string is K-Palindrome or not | Set 2
Given a string, find out if the string is K-Palindrome or not. A K-palindrome string transforms into a palindrome on removing at most k characters from it.Examples: Input : String - abcdecba, k = 1 Output : Yes String can become palindrome by removing 1 character i.e. either d or e Input : String -
8 min read
Find if string is K-Palindrome or not | Set 1
Given a string S, find out if the string is K-Palindrome or not. A K-palindrome string transforms into a palindrome on removing at most K characters from it.Examples : Input: S = "abcdecba", k = 1Output: YesExplanation: String can become palindrome by removing 1 character i.e. either d or e. Input:
15+ min read
Smallest and Largest Palindrome with N Digits
Given a number N. The task is to find the smallest and largest palindromic number possible with N digits.Examples: Input: N = 4 Output: Smallest Palindrome = 1001 Largest Palindrome = 9999 Input: N = 5 Output: Smallest Palindrome = 10001 Largest Palindrome = 99999 Smallest N-digit Palindromic Number
4 min read
Palindromic divisors of a number
Prerequisite: Find all divisors of a natural number Given a number N. The task is to find all the palindromic divisors of N. Examples: Input: N = 66 Output: 1 2 3 6 11 22 33 66 Input: N = 808 Output: 1 2 4 8 101 202 404 808 Approach: Find all the divisors of N using approach discussed in this articl
7 min read
Probability that a N digit number is palindrome
Given an integer N, the task is to find the probability that a number with a number of digits as N is a palindrome. The number may have leading zeros.Examples: Input: N = 5 Output: 1 / 100Input: N = 6 Output: 1 / 1000 Recommended: Please try your approach on {IDE} first, before moving on to the solu
9 min read
Length of Longest Palindrome Substring
Given a string S of length N, the task is to find the length of the longest palindromic substring from a given string. Examples: Input: S = "abcbab"Output: 5Explanation: string "abcba" is the longest substring that is a palindrome which is of length 5. Input: S = "abcdaa"Output: 2Explanation: string
15+ min read