Javatpoint Logo
Javatpoint Logo

Find the Closest Palindrome

Problem Statement:

Given a string n representing an integer, return the closest Integer (not including itself), which is a palindrome. If there is a tie, return the smaller one.

The closest is defined as the absolute difference minimized between two integers.

Java Approach 1 Using Binary search

Output:

Find the Closest Palindrome

Code Explanation:

  • This Java program finds the nearest palindromic number to a given input by performing a binary search for the closest palindromic candidates. The nearestPalindromic Method converts the input string to a long, then uses binary search (bs method) to locate the closest palindromes on either side.
  • The best Method compares the absolute differences to determine the nearest palindrome. The code leverages efficient digit-wise reconstruction (reconstruct Method) to form palindromes.

Time Complexity:

  • The time complexity is O(log10(N)), where N is the input number. This is due to the binary search (BS method) performed on the numeric range to find the nearest palindromes. The digit-wise reconstruction and comparison operations contribute to the logarithmic complexity

Space Complexity:

  • The space complexity is O(1), indicating constant space usage. The program uses a minimal amount of additional space for variables and does not depend on the size of the input. The recursive nature of the binary search contributes little to the space complexity.

Java Approach Using the Greedy Approach

Output:

Find the Closest Palindrome

Code Explanation:

  • The code determines the nearest palindromic number to the given input integer by checking the closest smaller and larger palindromic numbers. It converts the input to an integer, iterates to find the nearest smaller and larger palindromic numbers, and compares the distances.
  • The program returns the closest palindromic number. The isPalindrome Method verifies if a string is a palindrome.

Time complexity:

  • The time complexity is constant, O(1), as the algorithm iterates a fixed number of times to find the nearest smaller and larger palindromic numbers, and the input size doesn't impact the iteration count.

Space Complexity:

  • The space complexity is also constant, O(1), since the algorithm uses a limited number of variables and doesn't rely on dynamic data structures. The memory requirements remain constant irrespective of the input size, making the algorithm efficient in terms of both time and space.






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA