Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Closest Palindrome

HardPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Closest Palindrome. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

The Uber Drivers app occasionally formats numeric values such as driver-facing trip references in a way that benefits from a nearby palindromic value. Given a positive integer as a decimal string, return the closest different positive-or-zero palindrome.

If two palindromes are equally close, return the smaller one.

Formal Specification

Implement closest_palindrome(n), where n is a decimal string with no leading zeros unless n is "0". Return a decimal string representing the palindrome p that minimizes abs(int(n) - int(p)), subject to p != n.

The result may be "0". You may use integer arithmetic within the stated constraints.

Constraints

  • 1 <= len(n) <= 18
  • n contains only decimal digits
  • n has no leading zeros unless it is "0"
  • The input represents a non-negative integer
  • The answer must be different from the input

Function Signature

def closest_palindrome(n):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output