Find Palindrome With Fixed Length

Find Palindrome With Fixed Length

Given an integer array queries and a positive integer intLength, return an array answer where answer[i] is either the queries[i]<sup>th</sup> smallest positive palindrome of length intLength or -1 if no such palindrome exists.

A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros.

LeetCode Problem - 2217

class Solution {
    // Method to find k-th palindrome numbers for given queries and integer length
    public long[] kthPalindrome(int[] queries, int intLength) {
        // Array to store results
        long[] ans = new long[queries.length];

        // Calculate half length and whether it's even or odd
        int half = (intLength + 1) / 2;
        boolean even = intLength % 2 == 0;

        // Calculate the start and end range for palindromes
        long start = (long) Math.pow(10, half - 1);
        long end = (long) Math.pow(10, half) - 1;

        // Iterate through queries
        for (int i = 0; i < queries.length; i++) {
            // Check if query is within valid range
            if (queries[i] <= end - start + 1) {
                // Generate the k-th palindrome and store in result array
                ans[i] = generatePalindrome(queries[i] + start - 1, even);
            } else {
                // If query exceeds range, store -1
                ans[i] = -1;
            }
        }
        // Return the result array
        return ans;
    }

    // Method to generate palindrome from given number and whether it's even or odd
    long generatePalindrome(long n, boolean even) {
        // Initialize result with given number
        long res = n;
        // If it's an odd palindrome, remove the last digit
        if (!even)
            n = n / 10;
        // Append the reverse of the remaining digits to generate the palindrome
        while (n > 0) {
            res = (res * 10) + (n % 10);
            n = n / 10;
        }
        // Return the palindrome
        return res;
    }
}

Did you find this article valuable?

Support Perf Insights by becoming a sponsor. Any amount is appreciated!