Show problems as
Classic problem #2384MediumHash TableStringGreedyCounting

Largest Palindromic Number

Real-world version: Largest Mirror Number From Tiles
Tracked in this browser only
Read Largest Palindromic Number on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A sign maker owns a tray of digit tiles, listed as the string tiles, one character per tile. The tiles may be laid out in any order, and tiles that are not wanted stay in the tray, but at least one tile must be laid.

The sign must read the same left to right as right to left. It must also read as an ordinary number, so it may not begin with a 0, with one exception: the sign consisting of the single tile 0 is allowed.

Return the largest number the sign maker can lay out, as a string. A longer sign always beats a shorter one, and among signs of the same length the larger number wins. The tray always allows at least one legal sign.

Examples

Example 1

Input
tiles = "614616"
Output
"61616"

The sign `61616` reads the same in both directions and needs three 6 tiles and two 1 tiles, all of which the tray holds. The 4 tile stays in the tray.

Example 2

Input
tiles = "0000"
Output
"0"

Every tile in the tray is a 0, and a sign may not open with a 0 unless it is the single tile `0`, which is the sign laid here.

Example 3

Input
tiles = "550"
Output
"505"

The sign `505` reads the same in both directions, uses both 5 tiles and the 0 tile, and opens with a 5 rather than a 0.

Constraints

  • 1 <= tiles.length <= 10^5
  • tiles consists of the digit characters '0' through '9' only.
  • The answer is returned as a string, so it may be far too long to hold in a number.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def largest_mirror(tiles: str) -> str:
Java
public String largestMirror(String tiles)