LeetCode 2217: Find Palindrome With Fixed Length Solution
Master LeetCode problem 2217 (Find Palindrome With Fixed Length), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To solve this problem, we need to generate palindromes of a fixed length and return the k-th smallest palindrome for each query in the input array. We can follow the steps below:
- Start generating palindromes from the smallest palindrome of the given length.
- Keep track of the count of valid palindromes.
- For each query in the input array, find the k-th valid palindrome.
Solution Code
import java.util.*;
class Solution {
public int[] findPalindromes(int[] queries, int intLength) {
int n = queries.length;
int[] answer = new int[n];
int count = 0;
for (int num = (int)Math.pow(10, intLength - 1); count < queries[n - 1]; num++) {
String s = String.valueOf(num);
String rev = new StringBuilder(s).reverse().toString();
if (s.equals(rev)) {
count++;
if (count == queries[0]) {
answer[0] = num;
}
for (int i = 1; i < n; i++) {
if (count == queries[i]) {
answer[i] = num;
}
}
}
}
return answer;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2217 (Find Palindrome With Fixed Length)?
This page provides optimized solutions for LeetCode problem 2217 (Find Palindrome With Fixed Length) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2217 (Find Palindrome With Fixed Length)?
The time complexity for LeetCode 2217 (Find Palindrome With Fixed Length) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2217 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2217 in Java, C++, or Python.