![]() |
VOOZH | about |
Given a integer k, find the sum of first k even-length palindrome numbers.
Even length here refers to the number of digits of a number is even.
Examples:
Input : k = 3 Output : 66 Explanation: 11 + 22 + 33 = 66 (Sum of first three even-length palindrome numbers) Input : 10 Output : 1496 Explanation: 11+22+33+44+55+66+77+88+ 99+1001 = 1496
A naive approach will be to check every even length number, if it is a palindrome number then we sum it up. We repeat the same process for first K even length palindrome numbers and sum them up to get the sum.
In this case complexity will go high as even length numbers are from 10-99 and then 1000-9999 and then so on...
10-99, 1000-9999, 100000-999999.. has 9, 90, 900 respectively palindrome numbers in them, so to check k numbers we have to check a lot of numbers which will not be efficient enough.
An efficient approach will be to observe a pattern for even length prime numbers.
11, 22, 33, 44, 55, 66, 77, 88, 99, 1001, 1111, 1221, 1331, 1441, 1551, 1661...
1st number is 11, 2nd is 22, third is 33, 16th is 16-rev(16) i.e., 1661.
So the Nth number will int(string(n)+rev(string(n)).
See here for conversion of integer to string and string to integer.
Below is the implementation of the above approach:
66
Time Complexity: O(k*log10k), as we are using a loop to traverse k times and we are using the reverse() function in each traversal which will cost O(log10k) as the maximum size of the string we are reversing will be log10k.
Auxiliary Space: O(log10k), as we are using extra space for string of size log10k.
1. Initialize a variable sum to 0 to keep track of the sum of the palindrome numbers.
2. Initialize a counter variable count to 0 to keep track of the number of palindrome numbers found so far.
3. Initialize a variable i to 1 to start iterating from the first positive integer.
4. Repeat the following steps until count reaches K:
a. Convert the integer i to a string and check if it is a palindrome. If it is, add it to sum and increment count.
b. Increment i to check the next positive integer.
Once count reaches K, sum will contain the sum of the first K even-length palindrome numbers.
Sum of first 5 even-length palindrome numbers: 165
Time Complexity: O(K*N) where K is the number of even-length palindrome numbers to find and N is the maximum number of digits in any of the palindrome numbers.
Auxiliary Space: O(N) since we only need to store the string representation of each number.