KatInterview

Find Next Palindrome Number

StringsAuto-graded · 29 test cases
MediumAuto-gradedStringspalindromestring-manipulationgreedy

Last updated

Tests string manipulation and numeric logic to determine if a number is palindromic and compute the next larger palindrome efficiently.

You are given a string num representing a positive integer. Your task is to:

  1. Determine whether num represents a palindromic number
  2. Find the smallest palindromic number that is strictly larger than num

Return a list containing two elements: a boolean indicating whether the input is a palindrome, followed by a string representing the next larger palindrome.

Notes

  • The input is always a valid positive integer with no leading zeros
  • The result may be too large for standard integer types, so work with strings throughout
  • When the input is already palindromic, you must find the next palindrome after it, not return the input itself

Constraints

  • 1 <= len(num) <= 10^5
  • num consists only of digits '0' through '9'
  • num does not have leading zeros

Examples

Example 1

Input: find_next_palindrome('121')

Output: [True, '131']

Example 2

Input: find_next_palindrome('999')

Output: [True, '1001']

Example 3

Input: find_next_palindrome('12345')

Output: [False, '12421']

Example 4

Input: find_next_palindrome('1221')

Output: [True, '1331']

Hints

Hint 1

A palindrome is determined entirely by its first half—the second half is just a mirror

Hint 2

When all digits are 9, the next palindrome must have one more digit

Hint 3

Try mirroring the left half to the right; if that's not large enough, increment the middle portion and mirror again