Katkat

Check palindrome and find next larger palindrome

MicrosoftSoftware Engineer · Technical Screen

Last updated

This question tests string manipulation, edge-case handling, and algorithmic efficiency in generating the smallest palindrome greater than a given numeric string.

Problem Statement

Given a positive integer represented as a string s, perform two tasks:

  1. Return True if s is a palindrome, otherwise False.
  2. Find the smallest palindrome strictly greater than s. If the input is already a palindrome, you must return the next smallest palindrome larger than it. The output should be returned as a string.

Constraints

  • 1 <= len(s) <= 10^5
  • The string contains only digits 0-9.
  • The result might exceed the range of a 64-bit integer, so treat it as a string.

Examples

Example 1

  • Input: s = "121"
  • Output: "131"
  • Explanation: "121" is a palindrome. The next larger palindrome is "131".

Example 2

  • Input: s = "999"
  • Output: "1001"
  • Explanation: For numbers consisting only of 9s, the next palindrome is always 1 followed by n-1 zeros and a 1.

Implementation

def get_next_palindrome(s: str) -> str:
    # Return a tuple: (is_palindrome: bool, next_palindrome: str)
    pass

Hints

Hint 1

To check if a string is a palindrome, compare it with its reverse or use a two-pointer approach starting from both ends.

Hint 2

For finding the next palindrome, consider the middle of the string and increment the prefix; copy the prefix to the suffix while maintaining symmetry.

Hint 3

Handle the edge cases where incrementing the middle causes a carry-over, such as '999' becoming '1001' or '19' becoming '22'.

Follow-up questions

  • How would your approach change if you needed to find the nearest palindrome (either smaller or larger) instead of just the next larger one?
  • What is the time complexity of your solution, and can you optimize it if the input string is very large?
  • How would you handle leading zeros if the input was given as a numeric string that could potentially have them?