627. Before and After Puzzle

Create a list of Before and After puzzles based on a list of phrases.

A string made up entirely of lowercase English letters and spaces is called a phrase. Neither the beginning nor the end of a phrase contain a gap. A phrase does not contain consecutive spaces.

Phrases that are created by combining two phrases where the final word of the first phrase is the same as the first word of the second phrase are known as before and after puzzles.

For each pair of phrases, phrases[i] and phrases[j], where i!= j, return the Before and After puzzles that can be created. Keep in mind that the order in which two sentences match is important; we want to take into account both orders.

A list of unique strings arranged lexicographically should be the result of your query. 

Example 1:

Input: phrases = ["writing code", "code rocks"]

Output: ["writing code rocks"]

Explanation:

"writing code" and "code rocks" share "code" as a common word.

We can concatenate them into "writing code rocks".

No phrase is a predecessor of another in the final result.

Example 2:

Input: phrases = ["a", "b", "a b", "a b c", "c"]

Output: ["a b", "a b c"]

Explanation:

The valid before and after puzzles are:

  • "a" and "a b" share the word "a", so they form "a b".
  • "a" and "a b c" share the word "a", so they form "a b c".
  • "a b" and "b" share the word "b", so they form "a b".
  • "a b c" and "c" share the word "c", so they form "a b c".

After removing duplicates and sorting lexicographically, the final answer is:

  • ["a b", "a b c"]

Now Your Turn!

Pick the correct output for the given input

Input: phrases = ["dog", "dog cat fish"]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= phrases.length <= 100
  • 1 <= phrases[i].length <= 100

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
vector<string> beforeAndAfterPuzzles(vector<string>& phrases) {
// Your Code Goes Here
}
};
Test Case

Input:

Phrases