MediumNo. 1181LeetCode Premium

Before and After Puzzle — LeetCode 1181 Python Solution

Pattern
Sorting
Topics
Array, Hash Table, String, Sorting
Reading time
2 min

The problem

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.

Python solution

PythonSolution
class Solution:
    def beforeAndAfterPuzzles(self, phrases: List[str]) -> List[str]:
        ps = []
        for p in phrases:
            ws = p.split()
            ps.append((ws[0], ws[-1]))
        n = len(ps)
        ans = []
        for i in range(n):
            for j in range(n):
                if i != j and ps[i][1] == ps[j][0]:
                    ans.append(phrases[i] + phrases[j][len(ps[j][0]) :])
        return sorted(set(ans))

Complexity

Time
O(n2 × m × (log n + log m))
Space · auxiliary
O(n2 × m)

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1181. Before and After Puzzle is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0049Group AnagramsMedium
0522Longest Uncommon Subsequence IIMedium
0692Top K Frequent WordsMedium
0720Longest Word in DictionaryMedium
0721Accounts MergeMedium
0792Number of Matching SubsequencesMedium

Frequently asked questions

How hard is LeetCode 1181. Before and After Puzzle?

LeetCode 1181. Before and After Puzzle is rated Medium on LeetCode.

What is the time complexity of LeetCode 1181. Before and After Puzzle?

The Python solution on this page runs in O(n2 × m × (log n + log m)).

What is the space complexity of LeetCode 1181. Before and After Puzzle?

The Python solution on this page uses O(n2 × m) auxiliary space.

What topics does LeetCode 1181. Before and After Puzzle cover?

LeetCode 1181. Before and After Puzzle is tagged Array, Hash Table, String and Sorting on LeetCode.

Is LeetCode 1181. Before and After Puzzle a premium problem?

Yes. LeetCode 1181. Before and After Puzzle is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.