Given a non-negative palindromic number num containing n number of digits. The problem is to apply at most two swap operations on the number num so that the resultant is the largest possible palindromic number.
Input : 4697557964 Output : 9647557469 In, 4697557964 the highlighted digits were swapped to get the largest palindromic number 9647557469. Input : 54345 Output : 54345 No swapping of digits required.
Approach: If n < 3, then num itself is the largest possible palindromic number. Else calculate mid = (n / 2) – 1. Then create an array rightMax of size (mid + 1). rightMax[i] contains the index of the greatest digit which is on the right side of num[i] and also greater than num[i] and 0 <= i <= mid. If no such digit exists then rightMax[i] = -1. Now, traverse the rightMax array from i = 0 to m, and find the first element having rightMax[i] != -1. Perform the swap(num[i], num[rightMax[i]]) and swap(num[n – i – 1], num[n – rightMax[i] – 1]) operations and break.
Largest Palindrome: 9647557469
Time Complexity: O(n).
Auxiliary Space: O(n).
- Largest even number that can be formed by any number of swaps
- Largest palindromic number in an array
- Largest palindromic number by permuting digits
- Form the largest number using at most one swap operation
- Largest palindromic prime in an array
- Find the lexicographically largest palindromic Subsequence of a String
- Next higher number using atmost one swap operation
- Find the count of palindromic sub-string of a string in its sorted form
- Maximum number formed from array with K number of adjacent swaps allowed
- Make palindromic string non-palindromic by rearranging its letters
- Minimum number of adjacent swaps to convert a string into its given anagram
- Longest Palindromic Substring using Palindromic Tree | Set 3
- Number of palindromic permutations | Set 1
- Number of palindromic paths in a matrix
- Next higher palindromic number using the same set of digits
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.