Social feed~12 min2s · 256 MBtarget O(n) time, O(n) spacestrings
A social app has a playful "mirror" button. Tapping it flips every word of a caption back to front, so that "hello" becomes "olleh". The words keep their places, and so do the spaces between them.
You build the function behind the button. Captions are plain letters and digits, with spaces between the words.
Write mirror_words(caption).
Input: caption = "tap to flip"
Output: "pat ot pilf"The table shows each word before and after.
| Word | Mirrored |
|---|---|
| tap | pat |
| to | ot |
| flip | pilf |
The words stay in their places and each one is reversed. The single spaces stay too.
Input: caption = "a bc"
Output: "a cb"The two spaces between the words are kept. Only bc changes, to cb.
Input: caption = "x"
Output: "x"A word of one letter reads the same backwards.
1 ≤ caption.length ≤ 1,000,000 (characters)A million characters need a linear pass at most. Reversing one word costs about its length, and the words together add up to the length of the caption, so the whole task is O(n). Building each reversed word by adding letters to the front costs about length × length per word, and a single long word makes that too slow.