Chat app~15 min2s · 256 MBtarget O(n * L) time, O(n * L) spacestrings
A chat app lets people send short reaction codes. A code is a few lowercase letters. The app has a special effect when a code is followed later by the same code written backwards, for example ab and then ba.
Your team lead wants to know how many such pairs a chat contains. The codes are given in the order they were sent.
Write mirror_pairs(codes).
i < j such that codes[j] is codes[i] written backwards.aa, can pair with an earlier copy of itself.Input: codes = ["ab", "ba", "cd", "dc", "ab"]
Output: 3The codes are ab, ba, cd, dc and ab. Three pairs have a later code that is the earlier one reversed.
| Pair of positions | Earlier code reversed | Later code | Pair? |
|---|---|---|---|
| 1 and 2 | ba |
ba |
yes |
| 2 and 5 | ab |
ab |
yes |
| 3 and 4 | dc |
dc |
yes |
| 1 and 5 | ba |
ab |
no |
All the other pairs differ too. The answer is 3.
Input: codes = ["x"]
Output: 0A single code has no later code: no pair.
Input: codes = ["aa", "aa", "aa"]
Output: 3The code aa reads the same backwards. Each later copy pairs with each earlier one: positions 1 and 2, 1 and 3, 2 and 3. The answer is 3.
1 ≤ number of codes ≤ 10^51 ≤ length of each code ≤ 6a to zWith 10^5 codes there are about 5 x 10^9 pairs of positions. Comparing every pair is too slow.
If every code is a, every pair counts, and the answer is 4,999,950,000. That is more than a 32-bit integer holds, so the count needs a 64-bit number.