Before and After Puzzle - Problem
Imagine you're creating a word puzzle game where you combine two phrases into one by merging their overlapping words! This is exactly what a Before and After Puzzle does.
Given a list of phrases (strings with lowercase letters and spaces only), you need to find all possible Before and After combinations. Here's how it works:
- Take two different phrases where the last word of the first phrase matches the first word of the second phrase
- Merge them by combining the overlapping word (don't duplicate it!)
- For example:
"mission statement"+"statement of purpose"="mission statement of purpose"
Important rules:
- Order matters: both
phrases[i] + phrases[j]andphrases[j] + phrases[i]should be considered - A phrase cannot be combined with itself (
i โ j) - Return all unique combinations sorted lexicographically
Input & Output
example_1.py โ Python
$
Input:
["writing code", "code review"]
โบ
Output:
["writing code review"]
๐ก Note:
The last word of "writing code" is "code", which matches the first word of "code review". We merge them to get "writing code review" (note we don't duplicate "code").
example_2.py โ Python
$
Input:
["mission statement", "a quick bite to eat", "a chip off the old block", "chocolate chip cookie", "cookie monster"]
โบ
Output:
["a chip off the old block", "a quick bite to eat", "chocolate chip cookie monster"]
๐ก Note:
Multiple combinations are possible: "chocolate chip" + "chip off the old block", "a quick bite to" + "to eat" (but "to eat" is not in the input), and "chocolate chip cookie" + "cookie monster".
example_3.py โ Python
$
Input:
["a", "aa", "aaa"]
โบ
Output:
["a aa", "a aaa", "aa aaa"]
๐ก Note:
Edge case with single words: "a" + "aa" = "a aa", "a" + "aaa" = "a aaa", "aa" + "aaa" = "aa aaa".
Constraints
- 1 โค phrases.length โค 100
- 1 โค phrases[i].length โค 1000
- All phrases contain only lowercase English letters and spaces
- No leading or trailing spaces
- No consecutive spaces within phrases
Visualization
Tap to expand
Understanding the Visualization
1
Map the Islands
Create a directory of all islands organized by their first building
2
Find Connections
For each island, look up which other islands can be reached from its last building
3
Build Bridges
Connect compatible islands by merging their buildings without duplicating the connecting point
Key Takeaway
๐ฏ Key Insight: Instead of checking every pair (O(nยฒ)), group phrases by first word in a hash map, then instantly find matches for any last word in O(1) time.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code