Grokking the Coding Interview: Patterns for Coding Questions

0% completed

Solution: Largest Palindromic Number

Problem Statement

Given a string s containing 0 to 9 digits, create the largest possible palindromic number using the string characters. It should not contain leading zeroes.

A palindromic number reads the same backward as forward.

If it's not possible to form such a number using all digits of the given string, you can skip some of them.

Examples

Example 1

  • Input: s = "323211444"
  • Expected Output: "432141234"
  • Justification: This is the largest palindromic number that can be formed from the given digits.

Example 2

  • Input: s = "998877"

.....

.....

.....

Like the course? Get enrolled and start learning!
Venkata Narayanan

Venkata Narayanan

· 3 years ago

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 (firstHal
Show 1 reply
Miguel

Miguel

· 2 years ago

Space complexity should be O(N). We construct and hold half of the palindrome, which at worst is N/2.

Mohammed Dh Abbas

Mohammed Dh Abbas

· 2 years ago

class Solution: def largestPalindromic(self, num: str) -> str: # count the frequencies of the numbers from 9 - 0 in a map def build_counter(): counter = {str(i): 0 for i in range(10)} for n in num: counter[n] += 1 return counter counter = build_counter() remain = 0 # store the largest remaining number first_half = [] # store the first left half of the result result = [] # for the entire result # loop for all the number from 9 to 0 in decreasing order for i in range(9,0, -1): div = counter[str(i)] // 2 # take the division result rem = counter[str(i)] % 2 # the remaining # repeat