Given a list of phrases, generate a list of Before and After puzzles.
A phrase is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a phrase.
Before and After puzzles are phrases that are formed by merging two phrases where the last word of the first phrase is the same as the first word of the second phrase. Note that only the last word of the first phrase and the first word of the second phrase are merged in this process.
Return the Before and After puzzles that can be formed by every two phrases phrases[i] and phrases[j] where i != j. Note that the order of matching two phrases matters, we want to consider both orders.
You should return a list of distinct strings sorted lexicographically, after removing all duplicate phrases in the generated Before and After puzzles.
Example 1:
Input: phrases = ["writing code","code rocks"]
Output: ["writing code rocks"]
Example 2:
Input: phrases = ["mission statement","a quick bite to eat","a chip off the old block","chocolate bar","mission impossible","a man on a mission","block party","eat my words","bar of soap"]
Output: ["a chip off the old block party","a man on a mission impossible","a man on a mission statement","a quick bite to eat my words","chocolate bar of soap"]
Example 3:
Input: phrases = ["a","b","a"]
Output: ["a"]
Example 4:
Input: phrases = ["ab ba","ba ab","ab ba"]
Output: ["ab ba ab","ba ab ba"]
Constraints:
1 <= phrases.length <= 1001 <= phrases[i].length <= 100When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
This solution finds all valid Before and After puzzles by checking each ordered pair of phrases. For every pair, we check if the last word of the first phrase matches the first word of the second phrase. If a match is found, the phrases are merged and stored in a set to avoid duplicates before being returned in sorted order.
Here's how the algorithm would work step-by-step:
def before_and_after_puzzles(phrases):
# Split each phrase into words to identify their first and last words
word_lists = [phrase.split() for phrase in phrases]
resulting_puzzles = set()
phrase_count = len(phrases)
# Compare every distinct pair of phrases in both directions
for first_index in range(phrase_count):
for second_index in range(phrase_count):
if first_index == second_index:
continue
first_phrase_words = word_lists[first_index]
second_phrase_words = word_lists[second_index]
# Merge when the last word of the first phrase matches the first word of the second
if first_phrase_words[-1] == second_phrase_words[0]:
combined_words = first_phrase_words + second_phrase_words[1:]
resulting_puzzles.add(" ".join(combined_words))
# Return the collected unique results sorted in lexicographical order
return sorted(resulting_puzzles)
This problem requires finding all valid combinations where the ending word of one phrase matches the beginning word of another. We evaluate every ordered pair of phrases at distinct indices, merge matching pairs by overlapping the shared word, and collect the outcomes in a set. Finally, we convert the set into a list and sort it lexicographically to produce the required result.
Here's how the algorithm would work step-by-step:
def before_and_after_puzzles(phrases):
# Split each phrase into words to easily inspect the first and last words.
parsed_phrases = [phrase.split(" ") for phrase in phrases]
result_set = set()
phrase_count = len(phrases)
# Iterate through all ordered pairs of distinct phrase indices.
for first_index in range(phrase_count):
for second_index in range(phrase_count):
if first_index == second_index:
continue
first_words = parsed_phrases[first_index]
second_words = parsed_phrases[second_index]
# Merge when the last word of the first phrase matches the first word of the second.
if first_words[-1] == second_words[0]:
merged_words = first_words + second_words[1:]
result_set.add(" ".join(merged_words))
# Return unique merged phrases sorted in lexicographical order.
return sorted(list(result_set))
| Case | How to Handle |
|---|---|
| Input phrases list is empty or contains only a single phrase | Return an empty list immediately because at least two phrases are required to form a combination |
| Phrases with only a single word | Split the string by spaces to extract the first and last words, which will be identical for single-word phrases |
| Identical phrases repeated multiple times in the input | Use a set or duplicate filtering mechanism to ensure the final output contains only unique combined phrases |
| A phrase whose last word matches its own first word combined with itself | Allow self-pairing if the phrase matches the condition so long as they are distinct indices or permitted by the problem rules |
| Multiple different phrases sharing the exact same first and last words | Iterate through all possible pairs to generate every valid Cartesian product combination for those matching boundary words |
| Large input size with thousands of long phrases | Use a hash map grouping phrases by their first words to achieve optimal time complexity well within interview limits |
| No valid combinations can be formed from the input phrases | Return an empty list after checking all potential pairs without finding any matching boundary words |
| Phrases with extra whitespace or mixed casing | Preserve original string formatting for the output while strictly comparing the extracted first and last words |