Skip to content

2217. Find Palindrome With Fixed Length

  • Time: $O(q)$
  • Space: $O(q)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
 public:
  vector<long long> kthPalindrome(vector<int>& queries, int intLength) {
    const int start = pow(10, (intLength + 1) / 2 - 1);
    const int end = pow(10, (intLength + 1) / 2);
    const int mul = pow(10, intLength / 2);
    vector<long long> ans;

    for (const int query : queries)
      if (start + query > end)
        ans.push_back(-1);
      else
        ans.push_back(getKthPalindrome(query, start, mul, intLength));

    return ans;
  }

 private:
  long getKthPalindrome(int query, int start, int mul, int intLength) {
    const long prefix = start + query - 1;
    return prefix * mul + reverse(intLength % 2 == 0 ? prefix : prefix / 10);
  }

  long reverse(int num) {
    long res = 0;
    while (num > 0) {
      res = res * 10 + num % 10;
      num /= 10;
    }
    return res;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
  public long[] kthPalindrome(int[] queries, int intLength) {
    final int start = (int) Math.pow(10, (intLength + 1) / 2 - 1);
    final int end = (int) Math.pow(10, (intLength + 1) / 2);
    final int mul = (int) Math.pow(10, intLength / 2);
    long[] ans = new long[queries.length];

    for (int i = 0; i < queries.length; ++i)
      if (start + queries[i] > end)
        ans[i] = -1;
      else
        ans[i] = getKthPalindrome(queries[i], start, mul, intLength);

    return ans;
  }

  private long getKthPalindrome(int q, int start, int mul, int intLength) {
    final long prefix = start + q - 1;
    return prefix * mul + reverse(intLength % 2 == 0 ? prefix : prefix / 10);
  }

  long reverse(long num) {
    long res = 0;
    while (num > 0) {
      res = res * 10 + num % 10;
      num /= 10;
    }
    return res;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  def kthPalindrome(self, queries: list[int], intLength: int) -> list[int]:
    start = pow(10, (intLength + 1) // 2 - 1)
    end = pow(10, (intLength + 1) // 2)
    mul = pow(10, intLength // 2)

    def reverse(num: int) -> int:
      res = 0
      while num:
        res = res * 10 + num % 10
        num //= 10
      return res

    def getKthPalindrome(query: int) -> int:
      prefix = start + query - 1
      return prefix * mul + reverse(prefix
                                    if intLength % 2 == 0 else prefix // 10)

    return [-1 if start + query > end else getKthPalindrome(query)
            for query in queries]