Back to course home
0% completed
Vote For New Content
A glitch in the solution provided !!!
Venkata Narayanan
Jan 11, 2024
There is a small issue in the solution provided. if the input is "0009", then the output should be 9 (which is largest palindromic number) but this solution returns "0", as the first half is full zeroes. May be the below code will help.
class Solution {
largestPalindromic(num) {
const freq = {};
let firstHalf = '',
middle = '';
for (let i = 0; i < num.length; i++) {
freq[num[i]] = (freq[num[i]] || 0) + 1;
}
for (let i = 9; i >= 0; i--) {
if (freq[i] && freq[i] % 2 !== 0 && middle === '') {
middle = i.toString();
}
firstHalf += i.toString().repeat(Math.floor(freq[i] / 2));
}
if (firstHalf === '' ||firstHalf.match(/^0+$/) ) {
return middle === '' ? 0 : middle;
}
/* else if (firstHalf.match(/^0+$/)) {
return 0;
} */
return firstHalf + middle + [...firstHalf].reverse().join('');
}
}
0
0
Comments
Comments
Shubham Voraa year ago
It is fixed! Please, check updated code.
On this page