#2217
Find Palindrome With Fixed Length
MediumArrayMathMathString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of generating all palindromes, we can construct them directly using the first half of the number. This is efficient and avoids unnecessary checks.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the number of palindromes of the given length using the formula: 9 * 10^(ceil(intLength/2) - 1).
- 2Step 2: For each query, check if it exceeds the total number of palindromes; if so, return -1.
- 3Step 3: Construct the palindrome using the first half digits derived from the query.
solution.py15 lines
1def kthPalindrome(queries, intLength):
2 half_length = (intLength + 1) // 2
3 total_palindromes = 9 * (10 ** (half_length - 1))
4 answer = []
5 for q in queries:
6 if q > total_palindromes:
7 answer.append(-1)
8 else:
9 first_half = str(10**(half_length - 1) + q - 1)
10 if intLength % 2 == 0:
11 palindrome = first_half + first_half[::-1]
12 else:
13 palindrome = first_half + first_half[-2::-1]
14 answer.append(int(palindrome))
15 return answerℹ
Complexity note: The time complexity is O(n) because we directly compute the palindromes without generating all of them, making it efficient for large inputs.
- 1Palindromes can be constructed from their first half, reducing the need to check every number.
- 2The number of palindromes of a given length can be calculated mathematically.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.