Taro Logo

Before and After Puzzle

#1 Most AskedMedium
0 views
Topics:
ArraysStrings

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 <= 100
  • 1 <= phrases[i].length <= 100

Solution


Clarifying Questions

When 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:

  1. How are words defined within a phrase? Can we assume they are strictly space-separated, or should we handle punctuation and multiple consecutive spaces?
  2. Is the matching of the last word of the first phrase and the first word of the second phrase case-sensitive, or should we normalize the case?
  3. When a phrase's last word matches its first word, can it be combined with itself, and does the combined phrase drop the duplicated word or keep both?
  4. If two phrases can be combined, should the resulting string retain any extra spaces, or should words be joined by a single space?
  5. How should duplicate combined phrases resulting from different pairs of input phrases (or duplicate input phrases) be handled in the output?

Brute Force Solution

Approach

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:

  1. Pre-split every phrase into an array of words to easily access the boundary words.
  2. Initialize a set to collect all uniquely generated merged phrases.
  3. Iterate through all pairs of phrases with distinct indices to consider both possible orders.
  4. Check whether the final word of the first phrase equals the initial word of the second phrase.
  5. Merge the two word lists by dropping the duplicate connecting word and join them into a string.
  6. Sort the unique puzzle strings lexicographically and return the resulting list.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(N^2 * L) – We iterate through all pairs of phrases, which takes O(N^2) time for N phrases. For each valid pair, splitting, comparing boundary words, and merging strings take time proportional to the length of the phrases L. Sorting the resulting unique phrases adds an O(U * L * log U) term where U <= N^2 is the number of unique puzzles.
Space Complexity
O(N * L + U * L) – Storing the split word lists requires O(N * L) space, and storing the unique generated puzzles in a set requires O(U * L) space where U is the number of unique generated puzzles.

Optimal Solution

Approach

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:

  1. Split each phrase in the input list by spaces into a list of words for fast access to the first and last elements.
  2. Initialize an empty set to collect unique merged puzzle strings.
  3. Loop over all pairs of distinct indices to consider both possible relative orderings for any two phrases.
  4. Check if the final word of the first phrase equals the initial word of the second phrase.
  5. Concatenate the first phrase's words with the remaining words of the second phrase and add the merged phrase to the set.
  6. Sort the distinct merged phrases lexicographically and return the resulting list.

Code Implementation

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))

Big(O) Analysis

Time Complexity
O(N^2 * L + K log K) – With N phrases each of maximum length L, splitting takes O(N * L). There are N * (N - 1) ordered pairs checked, each taking O(L) to compare and merge words. Sorting the K resulting unique phrases takes O(K log K * L) where K <= N^2.
Space Complexity
O(N * L + K * L) – Storing the parsed phrases uses O(N * L) space, and storing up to K unique generated puzzle strings in the result set and output list requires O(K * L) space.

Edge Cases

Input phrases list is empty or contains only a single phrase
How to Handle:
Return an empty list immediately because at least two phrases are required to form a combination
Phrases with only a single word
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Return an empty list after checking all potential pairs without finding any matching boundary words
Phrases with extra whitespace or mixed casing
How to Handle:
Preserve original string formatting for the output while strictly comparing the extracted first and last words
0/1 completed