Grokking the Coding Interview: Patterns for Coding Questions

0% completed

Largest Palindromic Number (medium)

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!
D

Davide Pugliese

· 2 years ago

         TreeMap<Integer, Integer> map = new TreeMap<>((a, b) -> b - a);         for (int i = 0; i < num.length(); i++) {             var key = num.charAt(i) - '0';              System.out.println("Key above is: " + key);             map.put(key, map.getOrDefault(key, 0) + 1);         }         boolean odd = false;         int k = -1;         Deque<Character> stack = new ArrayDeque<>();         Deque<Character> queue = new ArrayDeque<>();         for (var entry: map.entrySet()) { var key = entry.getKey(); for (int i = 0; i < entry.getValue() / 2; i++) { queue.offer((char)(key + (int)'0')); } if (entry.getValue() % 2 == 1 && odd == false) { k = key;
M

mailman14736

· 2 months ago

Your implementation of the solution checker is wrong.....

input: "00001" gives Expected: "0" when it clearly should be Expected "1".

Oddly enough, the example code in your solution page correctly outputs "1"