Similar Problems

Similar Problems not available

Strictly Palindromic Number - Leetcode Solution

Companies:

LeetCode:  Strictly Palindromic Number Leetcode Solution

Difficulty: Medium

Topics: math two-pointers  

Problem description:

Given an integer n, return whether any permutation of its digits makes n strictly palindromic.

A strictly palindromic number is one in which all digits are the same, except the middle digit which may be different.

Example 1:

Input: n = 1221 Output: true Explanation: One possible permutation is 2112 which forms a strictly palindromic number 21212.

Example 2:

Input: n = 12345 Output: false Explanation: There is no permutation of the digits that will make it strictly palindromic.

Solution:

To solve this problem, we will first identify the conditions for a number to be strictly palindromic:

  • All digits must be the same
  • The middle digit may be different

Thus, we need to check if any permutation of the digits of the given number satisfies these conditions.

We can implement this by first converting the integer to a string, and then sorting the characters in ascending order. Next, we iterate through the sorted characters to check if they are all the same, except the middle digit.

If the number of digits is odd, we ignore the middle digit. If the number of digits is even, we check if the two middle digits are the same.

If all the conditions are satisfied, we return true. Otherwise, we return false.

Here is the Python implementation of the solution:

def is_strictly_palindromic(n): digits = sorted(str(n)) middle_index = len(digits) // 2

if len(digits) % 2 == 0:
    if digits[middle_index] != digits[middle_index - 1]:
        return False
    middle_index -= 1

middle_digit = digits[middle_index]

for digit in digits:
    if digit != middle_digit:
        return False

return True

Time Complexity:

The time complexity of this solution is O(n log n), where n is the number of digits in the input number. This is because we need to sort the digits of the input number.

Space Complexity:

The space complexity of this solution is O(n), where n is the number of digits in the input number. This is because we convert the input number to a string, which requires O(n) space.

Strictly Palindromic Number Solution Code

1