Mid/Senior

Before and After Puzzle

Given a list of strings phrases, generate all possible before and after puzzles.

A before and after puzzle is created by choosing two different phrases phrases[i] and phrases[j] such that the last word of phrases[i] is equal to the first word of phrases[j]. The puzzle is formed by concatenating phrases[i] with phrases[j], but the shared word appears only once.

Return all distinct before and after puzzles in lexicographical order.

Example 1
Inputphrases = ["writing code","code rocks"]
Output["writing code rocks"]
The last word of writing code matches the first word of code rocks, so they combine into writing code rocks.
Example 2
Inputphrases = ["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"]
Each returned phrase is formed by merging two different phrases whose boundary words match, with duplicates removed and the result sorted lexicographically.

Constraints

  • 1 <= phrases.length <= 100
  • 1 <= phrases[i].length <= 100
  • phrases[i] consists of lowercase English letters and spaces
  • phrases[i] does not have leading or trailing spaces
  • All words in phrases[i] are separated by a single space

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate