Practice problem · easy
A social app has a daily word game. Each player gets a rack of letter tiles and lays some of them in a row. A row is a mirror when it reads the same from left to right and from right to left, such as level. It does not have to be a real word.
Your team lead asks: "How long is the longest mirror a player can lay from the rack?"
Write longest_mirror_length(tiles).
tiles is the rack, one lowercase letter for each tile, in any order.Input: tiles = "bookkeeper"
Output: 7Count the tiles of each letter first. A mirror uses equal tiles in pairs, one on each side of the middle, and at most one tile in the middle.
| Letter | Tiles | Whole pairs | Tiles left over |
|---|---|---|---|
| b | 1 | 0 | 1 |
| o | 2 | 1 | 0 |
| k | 2 | 1 | 0 |
| e | 3 | 1 | 1 |
| p | 1 | 0 | 1 |
| r | 1 | 0 | 1 |
There are 3 pairs, which is 6 tiles. Some tiles are left over, so one of them can go in the middle: 6 + 1 = 7. For example, ekobkoe is a mirror of length 7.
Input: tiles = "aabb"
Output: 4Two pairs and nothing left over. The mirror abba uses every tile.
Input: tiles = "xyz"
Output: 1No two tiles match, so there are no pairs. One tile goes down by itself.
1 ≤ len(tiles) ≤ 100,000tiles uses only the lowercase letters a to z.A rack can have 100,000 tiles. Each tile is used or not used, so a rack of n tiles has 2^n sets of tiles to try. Trying them all never finishes after about 30 tiles. The answer depends only on how many tiles each letter has, and counting the tiles takes 100,000 small steps.
longest_mirror_length · runs in your browserCoding is easiest on a laptop. On a phone, read, trace and try small edits.