Next Palindrome Using Same Digits

Find the next-greater palindrome using the same digit multiset as the input.

Hard
Time O(n) Space O(1)
LeetCode
5 min read
two-pointers string permutation

Problem#

Given a numeric palindrome string num, return the lexicographically next palindrome using the same digits, or "" if none exists.

Examples#

  • "1221""2112"
  • "32123"""
  • "45544554""54455445"

Constraints#

  • 1 <= num.length <= 10^5, palindrome, no leading zeros.

Hints#

Hint 1
Run next-permutation on the left half, then mirror to the right half.

Approach#

A palindrome is fully determined by its left half (and an optional middle character for odd length). The next palindrome is therefore the next permutation of the left half, mirrored. Standard std::next_permutation on the left half handles ordering; if it returns false, no greater palindrome exists.

Solution#

Next Palindrome
class Solution {
public:
string nextPalindrome(string num) {
int n = num.size();
int half = n / 2;
if (!next_permutation(num.begin(), num.begin() + half)) return "";
for (int i = 0; i < half; ++i) num[n - 1 - i] = num[i];
return num;
}
};

Editorial#

The bijection “palindrome ↔ left half + middle” reduces the problem to finding the next permutation of the left half. The middle character (if any) is fixed — palindromes with the same multiset and the same left half permutation share a middle digit. std::next_permutation rearranges in O(n) using its classic “find the pivot, swap with the next greater, reverse suffix” algorithm; mirroring is another O(n) pass. The “no answer” case happens exactly when the left half is already its largest permutation.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.