Given a number, find the next smallest palindrome
Last Updated :
22 Apr, 2025
Given a number, in the form of an array num[] of size n containing digits from 1 to 9(inclusive). The task is to find the next smallest palindrome strictly larger than the given number.
Examples:
Input: num[] = [9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2]
Output: [9, 4, 1, 8, 8, 0, 8, 8, 1, 4, 9]
Explanation: Next smallest palindrome is 9 4 1 8 8 0 8 8 1 4 9
Input: num[] = [2, 3, 5, 4, 5]
Output: [2, 3, 6, 3, 2]
Explanation: Next smallest palindrome is 2 3 6 3 2
There are three distinct types of input that need to be handled separately:
- The input number is a palindrome and consists entirely of 9s. For example, "9 9 9". The output should be "1 0 0 1".
- The input number is not a palindrome. For example, "1 2 3 4". The output should be "1 3 3 1".
- The input number is a palindrome but does not consist entirely of 9s. For example, "1 2 2 1". The output should be "1 3 3 1".
The solution for input type 1 is straightforward. The output consists of n+1 digits, where the outermost digits are 1, and all the digits in between are 0.
Now, let's focus on input types 2 and 3. The goal is to transform a given number into a greater palindrome. To understand the solution better, let's define the following two terms:
Left Side: This refers to the left half of the given number. For example, in "1 2 3 4 5 6", the left side is "1 2 3", and in "1 2 3 4 5", the left side is "1 2".
Right Side: This refers to the right half of the given number. For example, in "1 2 3 4 5 6", the right side is "4 5 6", and in "1 2 3 4 5", the right side is "4 5".
To convert a number into the next larger palindrome, we can either mirror the left side of the number or mirror the right side. However, simply mirroring the right side might not always result in the next larger palindrome. Therefore, we mirror the left side and copy it to the right side. There are specific cases that need to be handled separately, which can be broken down into the following steps:
Step-by-step Process:
Start with Two Indices: Begin with two indices, i
and j
. Index i
points to the middle two elements (or just the middle element if the length is odd). We move both indices away from the middle to compare corresponding elements of the left and right sides.
Ignore Matching Left and Right Side: Initially, ignore the part of the left side that mirrors the corresponding part of the right side. For example, if the number is "8 3 4 2 2 4 6 9", we ignore the middle four digits, and now i
points to 3 and j
points to 6.
Handle Different Cases:
Case 1: Indices Cross the Boundary: This happens when the number is already a palindrome. In this case, we increment the middle digit (or digits if the length is even) and propagate the carry towards the leftmost digit. We then mirror the left side onto the right. Example: For the number "1 2 9 2 1", we increment 9 to 10, carry the 1, and the new number becomes "1 3 0 3 1".
Case 2: Left and Right Side Digits Differ: Here, we mirror the left side to the right side and minimize the number to guarantee the next smallest palindrome. This case has two sub-cases:
- Sub-case 2.1: Left Side Copying is Enough: Sometimes, simply copying the left side to the right is enough, and no increment is needed. We check this by comparing the first unmatched digit in the left side with the corresponding right side digit. Example: For "7 8 3 3 2 2", the next palindrome is "7 8 3 3 8 7".
If the left side's unmatched digit is greater than the corresponding right side digit, just mirroring the left side to the right side works.
- Sub-case 2.2: Left Side Copying is Not Enough: In some cases, the left side’s unmatched digit is smaller than the corresponding right side digit. Here, we add 1 to the middle digit (or digits for even lengths), propagate the carry towards the leftmost digit, and mirror the left side to the right side. Example: For "9 4 1 8 7 9 7 8 3 2 2", the next palindrome is "9 4 1 8 8 0 8 8 1 4 9".
[Naive Approach] Check Palindrome Method - O(n^2) time and O(n) space
This approach aims to find the next palindrome greater than a given number. The process involves checking if the number is a palindrome and if not, modifying the digits to generate the next palindrome.
C++
#include <iostream>
#include <vector>
using namespace std;
int checkPalindrome(vector<int>& num) {
int n = num.size();
for (int i = 0; i < n / 2; ++i) {
if (num[i] != num[n - 1 - i]) {
return 0;
}
}
return 1;
}
vector<int> nextPalindrome(vector<int>& num) {
int n = num.size();
// Increase the number by 1 and check for palindrome
while (!checkPalindrome(num)) {
// Add 1 to the number
int carry = 1;
for (int i = n - 1; i >= 0; --i) {
num[i] += carry;
if (num[i] == 10) {
num[i] = 0;
carry = 1;
} else {
carry = 0;
break;
}
}
// If there's still a carry, insert 1 at the beginning
if (carry == 1) {
num.insert(num.begin(), 1);
n++;
}
}
return num;
}
int main() {
vector<int> num = {9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2};
vector<int> res = nextPalindrome(num);
for (int i = 0; i < res.size(); ++i) {
cout << res[i] << " ";
}
cout << endl;
return 0;
}
Java
import java.util.Arrays;
import java.util.ArrayList;
class GfG {
static int checkPalindrome(int[] num) {
int n = num.length;
for (int i = 0; i < n / 2; ++i) {
if (num[i] != num[n - 1 - i]) {
return 0;
}
}
return 1;
}
static ArrayList<Integer> nextPalindrome(int[] num) {
int n = num.length;
// Increase the number by 1 and check for palindrome
while (checkPalindrome(num) == 0) {
int carry = 1;
for (int i = n - 1; i >= 0; --i) {
num[i] += carry;
if (num[i] == 10) {
num[i] = 0;
carry = 1;
} else {
carry = 0;
break;
}
}
if (carry == 1) {
num = Arrays.copyOf(num, n + 1);
System.arraycopy(num, 0, num, 1, n);
num[0] = 1;
n++;
}
}
// Convert the array to ArrayList
ArrayList<Integer> result = new ArrayList<>();
for (int digit : num) {
result.add(digit);
}
return result;
}
public static void main(String[] args) {
int[] num = {9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2};
ArrayList<Integer> res = nextPalindrome(num);
for (int i : res) {
System.out.print(i + " ");
}
System.out.println();
}
}
Python
def checkPalindrome(num):
n = len(num)
for i in range(n // 2):
if num[i] != num[n - 1 - i]:
return 0
return 1
def nextPalindrome(num):
n = len(num)
# Increase the number by 1 and check for palindrome
while not checkPalindrome(num):
# Add 1 to the number
carry = 1
for i in range(n - 1, -1, -1):
num[i] += carry
if num[i] == 10:
num[i] = 0
carry = 1
else:
carry = 0
break
# If there's still a carry, insert 1 at the beginning
if carry == 1:
num.insert(0, 1)
n += 1
return num
if __name__ == '__main__':
num = [9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2]
res = nextPalindrome(num)
print(' '.join(map(str, res)))
C#
using System;
using System.Collections.Generic;
class GfG {
// Function to check if a number (as an array of digits) is a palindrome
static int checkPalindrome(int[] num) {
int n = num.Length;
for (int i = 0; i < n / 2; ++i) {
if (num[i] != num[n - 1 - i]) {
return 0;
}
}
return 1;
}
// Function to find the next palindrome number
static List<int> nextPalindrome(int[] num) {
int n = num.Length;
// Increase the number by 1 and check for palindrome
while (checkPalindrome(num) == 0) {
// Add 1 to the number
int carry = 1;
for (int i = n - 1; i >= 0; --i) {
num[i] += carry;
if (num[i] == 10) {
num[i] = 0;
carry = 1;
} else {
carry = 0;
break;
}
}
// If there's still a carry, insert 1 at the beginning
if (carry == 1) {
int[] newNum = new int[n + 1];
newNum[0] = 1;
Array.Copy(num, 0, newNum, 1, n);
num = newNum;
n++;
}
}
// Convert the array to List<int> and return it
List<int> result = new List<int>(num.Length);
foreach (int digit in num) {
result.Add(digit);
}
return result;
}
static void Main() {
// Initialize the number as a vector of digits
int[] num = { 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 };
// Get the next palindrome number
List<int> res = nextPalindrome(num);
// Output the result (space-separated digits)
foreach (int digit in res) {
Console.Write(digit + " ");
}
Console.WriteLine();
}
}
JavaScript
function checkPalindrome(num) {
const n = num.length;
for (let i = 0; i < Math.floor(n / 2); ++i) {
if (num[i] !== num[n - 1 - i]) {
return 0;
}
}
return 1;
}
function nextPalindrome(num) {
let n = num.length;
// Increase the number by 1 and check for palindrome
while (checkPalindrome(num) === 0) {
// Add 1 to the number
let carry = 1;
for (let i = n - 1; i >= 0; --i) {
num[i] += carry;
if (num[i] === 10) {
num[i] = 0;
carry = 1;
} else {
carry = 0;
break;
}
}
// If there's still a carry, insert 1 at the beginning
if (carry === 1) {
num.unshift(1);
n++;
}
}
return num;
}
// Driver Code
const num = [9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2];
const res = nextPalindrome(num);
console.log(res.join(' '));
Output9 4 1 8 8 0 8 8 1 4 9
[Expected Approach] Next Palindrome Generation using Mirror and Carry Propagation - O(n) time and O(n) space
The approach finds the next palindrome greater than a given number by:
- Checking if all digits are 9: If true, the next palindrome is simply
100...001
. - Mirroring the left side to the right side: If not, mirror the left part of the number onto the right side to form a palindrome.
- Checking if the mirrored number is greater: If it’s smaller or equal, increment the middle digits and propagate the carry towards the left side, then mirror again.
- Returning the result: The result is the next greater palindrome.
This approach works efficiently by utilizing the symmetry of palindromes and adjusting only when necessary.
C++
// C++ Program to generate the next palindrome of a given number
#include <iostream>
#include <vector>
using namespace std;
// A utility function to check if all digits in num[] are 9
int AreAll9s(const vector<int>& num) {
for (int i = 0; i < num.size(); ++i) {
if (num[i] != 9) return 0;
}
return 1;
}
// Function to generate the next palindrome
void nextPalindromeUtil(vector<int>& num) {
int n = num.size();
int mid = n / 2;
bool leftSmaller = false;
int i = mid - 1;
int j = (n % 2) ? mid + 1 : mid;
// Compare the left side with the right side
while (i >= 0 && num[i] == num[j]) i--, j++;
// Check if we need to increment the middle digit(s)
if (i < 0 || num[i] < num[j]) leftSmaller = true;
// Copy the left half to the right half
while (i >= 0) {
num[j] = num[i];
j++;
i--;
}
// If middle digits need to be incremented
if (leftSmaller) {
int carry = 1;
i = mid - 1;
if (n % 2 == 1) {
num[mid] += carry;
carry = num[mid] / 10;
num[mid] %= 10;
j = mid + 1;
} else {
j = mid;
}
while (i >= 0) {
num[i] += carry;
carry = num[i] / 10;
num[i] %= 10;
num[j++] = num[i--];
}
}
}
// Function to generate the next palindrome
vector<int> nextPalindrome(vector<int>& num) {
vector<int> ans;
if (AreAll9s(num)) {
ans.push_back(1);
for (int i = 1; i < num.size(); i++) ans.push_back(0);
ans.push_back(1);
} else {
nextPalindromeUtil(num);
for (int i = 0; i < num.size(); i++) {
ans.push_back(num[i]);
}
}
return ans;
}
int main() {
vector<int> num = {9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2};
vector<int> result = nextPalindrome(num);
for (int i : result) {
cout << i << " ";
}
cout << endl;
return 0;
}
Java
// Java Program to generate the next palindrome of a given number
import java.util.ArrayList;
public class GfG {
// Check if all digits in num[] are 9
public static int areAll9s(int[] num) {
for (int i = 0; i < num.length; i++) {
if (num[i] != 9) return 0;
}
return 1;
}
// Function to generate the next palindrome
public static void nextPalindromeUtil(int[] num) {
int n = num.length;
int mid = n / 2;
boolean leftSmaller = false;
int i = mid - 1;
int j = (n % 2) == 1 ? mid + 1 : mid;
// Compare left and right halves
while (i >= 0 && num[i] == num[j]) {
i--;
j++;
}
// Check if the middle digit(s) need to be incremented
if (i < 0 || num[i] < num[j]) leftSmaller = true;
// Copy the left side to the right side
while (i >= 0) {
num[j] = num[i];
j++;
i--;
}
// If middle digits need to be incremented
if (leftSmaller) {
int carry = 1;
i = mid - 1;
if (n % 2 == 1) {
num[mid] += carry;
carry = num[mid] / 10;
num[mid] %= 10;
j = mid + 1;
} else {
j = mid;
}
// Propagate the carry and mirror the left side to the right
while (i >= 0) {
num[i] += carry;
carry = num[i] / 10;
num[i] %= 10;
num[j++] = num[i--];
}
}
}
// Function to generate next palindrome
public static ArrayList<Integer> nextPalindrome(int[] num) {
ArrayList<Integer> result = new ArrayList<>();
if (areAll9s(num) == 1) {
result.add(1);
for (int i = 1; i < num.length; i++) {
result.add(0);
}
result.add(1);
} else {
nextPalindromeUtil(num);
for (int i = 0; i < num.length; i++) {
result.add(num[i]);
}
}
return result;
}
public static void main(String[] args) {
int[] num = {9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2};
ArrayList<Integer> result = nextPalindrome(num);
for (int i : result) {
System.out.print(i + " ");
}
System.out.println();
}
}
Python
# Python Program to generate the next palindrome of a given number
# Check if all digits are 9
def are_all_9s(num):
return all(digit == 9 for digit in num)
# Function to generate the next palindrome
def nextPalindromeUtil(num):
n = len(num)
mid = n // 2
left_smaller = False
i = mid - 1
j = mid + 1 if n % 2 else mid
# Compare left and right halves
while i >= 0 and num[i] == num[j]:
i -= 1
j += 1
# Check if the middle digit(s) need to be incremented
if i < 0 or num[i] < num[j]:
left_smaller = True
# Copy left half to the right half
while i >= 0:
num[j] = num[i]
j += 1
i -= 1
# If middle digits need to be incremented
if left_smaller:
carry = 1
i = mid - 1
if n % 2 == 1:
num[mid] += carry
carry = num[mid] // 10
num[mid] %= 10
j = mid + 1
else:
j = mid
# Propagate the carry to the left side
while i >= 0:
num[i] += carry
carry = num[i] // 10
num[i] %= 10
num[j] = num[i]
j += 1
i -= 1
# Function to generate next palindrome
def nextPalindrome(num):
if are_all_9s(num):
return [1] + [0] * (len(num) - 1) + [1]
else:
nextPalindromeUtil(num)
return num
if __name__ == "__main__":
num = [9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2]
result = nextPalindrome(num)
print(" ".join(map(str, result)))
C#
// C# Program to generate the next palindrome of a given number
using System;
using System.Collections.Generic;
class GfG {
// Check if all digits are 9
public static bool AreAll9s(int[] num) {
foreach (var digit in num) {
if (digit != 9) return false;
}
return true;
}
// Function to generate the next palindrome
public static void nextPalindromeUtil(int[] num) {
int n = num.Length;
int mid = n / 2;
bool leftSmaller = false;
int i = mid - 1;
int j = (n % 2 == 1) ? mid + 1 : mid;
// Compare left and right halves
while (i >= 0 && num[i] == num[j]) {
i--;
j++;
}
// Check if the middle digit(s) need to be incremented
if (i < 0 || num[i] < num[j]) leftSmaller = true;
// Copy the left half to the right half
while (i >= 0) {
num[j] = num[i];
j++;
i--;
}
// If middle digits need to be incremented
if (leftSmaller) {
int carry = 1;
i = mid - 1;
if (n % 2 == 1) {
num[mid] += carry;
carry = num[mid] / 10;
num[mid] %= 10;
j = mid + 1;
} else {
j = mid;
}
// Propagate the carry to the left side
while (i >= 0) {
num[i] += carry;
carry = num[i] / 10;
num[i] %= 10;
num[j++] = num[i--];
}
}
}
// Function to generate next palindrome
public static List<int> nextPalindrome(int[] num) {
List<int> result = new List<int>();
if (AreAll9s(num)) {
result.Add(1); // Start with 1
for (int i = 1; i < num.Length; i++) {
result.Add(0); // Add zeros
}
result.Add(1); // End with 1
} else {
nextPalindromeUtil(num); // Generate palindrome
for (int i = 0; i < num.Length; i++) {
result.Add(num[i]); // Store result
}
}
return result;
}
static void Main(string[] args) {
int[] num = {9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2};
var result = nextPalindrome(num);
Console.WriteLine(string.Join(" ", result));
}
}
JavaScript
// JavaScript Program to generate the next palindrome of a given number
// Check if all digits are 9
function areAll9s(num) {
return num.every(digit => digit === 9);
}
// Function to generate the next palindrome
function nextPalindromeUtil(num) {
let n = num.length;
let mid = Math.floor(n / 2);
let leftSmaller = false;
let i = mid - 1;
let j = (n % 2 === 1) ? mid + 1 : mid;
// Compare left and right halves
while (i >= 0 && num[i] === num[j]) {
i--;
j++;
}
// Check if the middle digit(s) need to be incremented
if (i < 0 || num[i] < num[j]) leftSmaller = true;
// Copy the left half to the right half
while (i >= 0) {
num[j] = num[i];
j++;
i--;
}
// If middle digits need to be incremented
if (leftSmaller) {
let carry = 1;
i = mid - 1;
if (n % 2 === 1) {
num[mid] += carry;
carry = Math.floor(num[mid] / 10);
num[mid] %= 10;
j = mid + 1;
} else {
j = mid;
}
// Propagate the carry to the left side
while (i >= 0) {
num[i] += carry;
carry = Math.floor(num[i] / 10);
num[i] %= 10;
num[j++] = num[i--];
}
}
}
// Function to return the next palindrome for a given number
function nextPalindrome(num) {
let n = num.length;
// If all digits are 9, return the next palindrome as 100...001
if (areAll9s(num)) {
return [1].concat(Array(n - 1).fill(0)).concat([1]);
}
nextPalindromeUtil(num);
return num;
}
// Driver Code
let num = [9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2];
let result = nextPalindrome(num);
console.log(result.join(" "));
Output9 4 1 8 8 0 8 8 1 4 9
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem