Ride-hailing app~12 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-266strings · hashing
A ride-hailing app prints a ticket code of lowercase letters on every ride receipt. The app runs a lucky-ride promotion. A ride is lucky when the letters of its code can be rearranged into a word that reads the same forwards and backwards.
Nobody has to write the rearranged word, only to say whether it exists. A code can be long, up to 1,000,000 letters, for example when many receipts of one trip are joined.
Write can_be_palindrome(code).
code uses only the lowercase letters a to z.true when some rearrangement of all the letters of code is a palindrome, a word that reads the same forwards and backwards.false.Input: code = "kayakmm"
Output: trueThe letters can make kayakmm into mkayakm, which reads the same both ways.
Count each letter, and look at the odd counts.
| Letter | Count | Odd? |
|---|---|---|
| a | 2 | no |
| k | 2 | no |
| m | 2 | no |
| y | 1 | yes |
Only one letter has an odd count, so it can go in the middle: mkayakm has m, k and a in pairs round the y.
Input: code = "ab"
Output: falseTwo different letters, each used once, cannot be arranged to read the same both ways.
Input: code = "z"
Output: trueA single letter is a palindrome.
1 ≤ code.length ≤ 1,000,000 (letters)code uses only the lowercase letters a to zCounting each letter of the code by scanning the whole code costs about n × n = 10^12 steps at n = 10^6. One pass costs about n steps. Trying every rearrangement is far worse still, because a code of n letters has up to n! orders.