1269. Square Word Pairs
A puzzle designer keeps a list of lowercase words in the array words, duplicates allowed. A string is a double when it is some string written twice in a row, such as abcabc or aa. The designer glues two list entries together and asks whether the result is a double.
Return the number of index pairs i < j for which the concatenation words[i] + words[j] is a double. Pairs of different positions count separately even if the words are equal.
The total length of all words is at most 200,000, so testing every pair is too slow. Aim for roughly O(total length) expected time and space, for example by hashing words and walking each word's borders.
Example 1
- Input:
- words = ["ab","ab","ba"]
- Output:
- 1
- Explanation:
Only the pair of equal words gives abab, which is a double; abba is not, so the answer is 1.
Example 2
- Input:
- words = ["b","aba","b"]
- Output:
- 3
- Explanation:
The pairs b + aba = baba, aba + b = abab and b + b = bb are all doubles, so the answer is 3.
Example 3
- Input:
- words = ["x","y"]
- Output:
- 0
- Explanation:
xy is not a double, so the answer is 0.
Constraints
1 ≤ words.length ≤ 105
The total length of all words is at most 2*105.
Words contain lowercase letters only and are non-empty.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(total length)
- Space
- O(total length)