Problem Description
Given a list of phrases, generate a list of Before and After puzzles. A puzzle is formed by merging two phrases where the last word of the first phrase is the same as the first word of the second phrase. The merged phrase is created by concatenating the two phrases but without repeating the common word. All valid pairs (with distinct indices and both orders) should be considered and the final list of puzzles must be distinct and sorted lexicographically.
Key Insights
- Extract the first and last word from each phrase.
- For every pair of phrases (i ≠ j), check if the last word of phrase[i] matches the first word of phrase[j].
- Merge the phrases by concatenating phrase[i] with phrase[j] (omitting the duplicate word at the start of phrase[j]).
- Use a set to automatically handle duplicate merged phrases.
- Finally, sort the set of results lexicographically before returning.
Space and Time Complexity
Time Complexity: O(n^2 * L) where n is the number of phrases and L is the average length of a phrase (due to splitting and concatenation). Space Complexity: O(u) where u is the number of unique puzzles stored, with additional O(n) space for storing first and last words.
Solution
The approach involves pre-processing each phrase to extract its first and last word. Then, using two nested loops, we iterate over all pairs of phrases (ensuring i ≠ j) and check if the last word of the first phrase is equal to the first word of the second. When a match is found, the two phrases are merged by taking the full first phrase and appending the second phrase starting just after its first word. This merged string is added to a set to guarantee uniqueness. Finally, the set is converted to a sorted list which is returned as the result. This method efficiently handles duplicate phrases and ensures that the final results are lexicographically ordered.