Before and After Puzzle

The problem requires us to form Before and After puzzles by joining two phrases in the provided list such that the last word of the first phrase is the same as the first word of the second phrase.

Python solution:

  1. Iterate through all the phrases and find phrases that have the same first word or last word.
  2. Create the puzzles by joining the phrases that meet the above condition, and store them in a set to eliminate duplicates.
  3. Return the sorted list of unique puzzles.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from typing import List

class Solution:
    def beforeAndAfterPuzzles(self, phrases: List[str]) -> List[str]:
        first_words = {}
        last_words = {}

        # Group phrases by first word and last word
        for i, phrase in enumerate(phrases):
            first_word, last_word = phrase.split()[0], phrase.split()[-1]
            first_words.setdefault(first_word, []).append(i)
            last_words.setdefault(last_word, []).append(i)

        # Generate puzzles by joining phrases with matching first and last words
        puzzles = set()
        for word, indexes in last_words.items():
            next_indexes = first_words.get(word, [])
            for i in indexes:
                for j in next_indexes:
                    if i != j:
                        # Create the puzzle and add it to the set
                        puzzle = phrases[i] + phrases[j][len(word):]
                        puzzles.add(puzzle)

        # Return the sorted list of unique puzzles
        return sorted(list(puzzles))

The returned list will contain the Before and After puzzles formed by every two phrases in the given list where the last word of one phrase is the same as the first word of another phrase, sorted lexicographically.