Split Strings by Separator — LeetCode 2788 Python Solution

EasyArrayString
Problem
#2788
Pattern
Hash Map
Reading time
2 min

The problem

Given an array of strings words and a character separator, split each string in words by separator. Return an array of strings containing the new strings formed after the splits, excluding empty strings.

Example

Input
words = ["one.two.three","four.five","six"], separator = "."
Output
["one","two","three","four","five","six"]
Explanation
In this example we split as follows:

Python solution

Python
class Solution:
    def splitWordsBySeparator(self, words: List[str], separator: str) -> List[str]:
        return [s for w in words for s in w.split(separator) if s]

Complexity

MeasureComplexity
TimeO(n \times m)
SpaceO(m), where n is the length of the string array words, and m is the maximum length of the strings in the array words auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2788. Split Strings by Separator is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2788. Split Strings by Separator?
LeetCode 2788. Split Strings by Separator is rated Easy on LeetCode.
What is the time complexity of LeetCode 2788. Split Strings by Separator?
The Python solution on this page runs in O(n \times m).
What is the space complexity of LeetCode 2788. Split Strings by Separator?
The Python solution on this page uses O(m), where n is the length of the string array words, and m is the maximum length of the strings in the array words auxiliary space.
What topics does LeetCode 2788. Split Strings by Separator cover?
LeetCode 2788. Split Strings by Separator is tagged Array and String on LeetCode.

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.

Get Stealth Interview