LeetCode 1842: Next Palindrome Using Same Digits
Problem Description
Explanation:
To find the next palindrome using the same digits as the input number, we can follow these steps:
- Convert the input number to a string and sort the digits in ascending order.
- Check if the sorted digits form a palindrome. If they do, increment the last digit by 1 and check if the new number is a palindrome. If not, repeat this process until a valid palindrome is found.
- If the sorted digits do not form a palindrome, we need to find the next larger palindrome that can be formed using the same digits. To do this, we divide the sorted digits into two halves: the left half and the right half. We mirror the left half to form the first half of the palindrome and mirror the right half to form the second half of the palindrome.
- If the resulting palindrome is larger than the original number, we have found the next larger palindrome using the same digits. If not, we need to increment the left half by 1 and repeat the process until we find a valid palindrome.
Time Complexity:
The time complexity of this algorithm is O(nlogn), where n is the number of digits in the input number.
Space Complexity:
The space complexity is O(n) to store the sorted digits.
:
Solutions
import java.util.Arrays;
class Solution {
public int nextPalindrome(int num) {
char[] digits = String.valueOf(num).toCharArray();
Arrays.sort(digits);
String sorted = new String(digits);
if (isPalindrome(sorted)) {
num++;
while (!isPalindrome(String.valueOf(num))) {
num++;
}
} else {
int n = digits.length;
int mid = n / 2;
StringBuilder left = new StringBuilder(new String(digits, 0, mid));
StringBuilder right = new StringBuilder(new String(digits, mid, n - mid));
String palindrome = left.toString() + right.reverse().toString();
int next = Integer.parseInt(palindrome);
while (next <= num) {
if (left.toString().equals("9".repeat(mid))) {
left = new StringBuilder("1" + "0".repeat(mid - 1));
} else {
left = new StringBuilder(String.valueOf(Integer.parseInt(left.toString()) + 1));
}
palindrome = left.toString() + left.reverse().toString();
next = Integer.parseInt(palindrome);
}
num = next;
}
return num;
}
private boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}
Loading editor...