Social feed~35 min2s · 256 MBtarget O(n L^2) time, O(n L) spaceclassic twin: lc-336strings · hashing
A social feed app has a trending list of hashtags. The product team is trying a "mirror post" badge. It goes to two hashtags posted one after the other when the letters, joined without the hash signs, read the same from both ends.
For example, ab followed by ba gives abba, which is a mirror. The order matters: ba followed by ab is another pair, and it is also a mirror.
Your team lead asks how many ordered pairs of different trending hashtags form a mirror.
Write count_mirror_pairs(tags).
tags holds distinct hashtags written in lowercase letters, without the hash sign.(i, j) with i != j such that tags[i] + tags[j] reads the same forwards and backwards.Input: tags = ["ab", "ba", "a", "aab"]
Output: 5The five pairs are ab + ba = abba, ba + ab = baab, ab + a = aba, a + ba = aba and ba + aab = baaab.
Cut every tag at each position into a front and a back. If the front is a palindrome, the tag reversed from the back, placed before this tag, makes a mirror. If the back is a palindrome, the tag reversed from the front, placed after it, makes a mirror. Here is the tag aab.
| Cut | Front | Back | Palindrome side | Tag looked for | Found? |
|---|---|---|---|---|---|
| 0 | (empty) | aab |
front | baa |
no |
| 1 | a |
ab |
front | ba |
yes: ba + aab |
| 2 | aa |
b |
front | b |
no |
| 2 | aa |
b |
back | aa |
no |
| 3 | aab |
(empty) | none |
Input: tags = ["noon"]
Output: 0noon is a palindrome, but a hashtag cannot pair with itself.
Input: tags = ["a", "aa", "aaa"]
Output: 6Every ordered pair of different tags forms a run of a, which reads the same both ways.
1 ≤ length of tags ≤ 10^41 ≤ length of tags[i] ≤ 30, lowercase letters onlyJoining every ordered pair and comparing it with its reverse makes about n^2 = 10^8 joins, each as long as 60 letters. That is far too slow.
A tag has at most 31 cuts. For each cut, a partner is fully decided: it must be one exact string. So check each cut against a set of all tags, in time proportional to the length of the tag.