imashutosh51

Find Palindrome With Fixed Length

Aug 29th, 2022 (edited)
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | None | 0 0
  1. '''
  2.    Rules:
  3.    1. A palindrome is fully determined by its first half.
  4.       - Even n → first half length = n // 2
  5.       - Odd n  → first half length = n // 2 + 1
  6.    2. The smallest valid first half (no leading zeros):
  7.       - Even n → start = 10**(n//2 - 1)
  8.       - Odd n  → start = 10**(n//2)
  9.    3. Compute the k-th first half:
  10.       first_half = start + (k - 1)
  11.    4. Form the palindrome by mirroring:
  12.       - Even n → palindrome = first_half + reversed(first_half)
  13.       - Odd n  → palindrome = first_half + reversed(first_half)[1:]
  14.    5. If the resulting palindrome length != n, return -1.
  15.    6. Use str() and [::-1] for string reversal, int() for final number.
  16. '''
  17.  
  18. class Solution:
  19.     def kthPalindrome(self, q: List[int], n: int) -> List[int]:
  20.         ans = []
  21.  
  22.         if n % 2:
  23.             start = pow(10, n // 2)
  24.         else:
  25.             start = pow(10, (n // 2) - 1)
  26.  
  27.         for i in range(len(q)):
  28.             first = str(start + q[i] - 1)
  29.             second = first[::-1]
  30.  
  31.             if n % 2:
  32.                 val = first + second[1:]
  33.                 if len(val) != n:
  34.                     ans.append(-1)
  35.                 else:
  36.                     ans.append(int(val))     # inbuilt conversion
  37.             else:
  38.                 val = first + second
  39.                 if len(val) != n:
  40.                     ans.append(-1)
  41.                 else:
  42.                     ans.append(int(val))     # inbuilt conversion
  43.  
  44.         return ans
  45.  
Advertisement
Add Comment
Please, Sign In to add comment