We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Split Strings by Separator

Number: 2881

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given an array of strings (words) and a character (separator), split each string by the given separator and return an array of the resulting substrings in order. Any empty strings resulting from the split should be excluded.


Key Insights

  • Process each string individually from the words array.
  • Use the built-in string split functionality to split by the separator.
  • Filter out any empty strings that result from splitting.
  • Maintain the order of substrings as they appear in the original array.

Space and Time Complexity

Time Complexity: O(n) where n is the total number of characters in all the given words, since each character is processed essentially once. Space Complexity: O(n) for storing the resulting substrings.


Solution

The solution involves iterating through each string in the words array, using the language's native split operation with the specified separator. After splitting, we filter out any empty strings (which might occur if the string starts, ends, or has consecutive separators). Append the non-empty substrings to the result list. Finally, return the result list. This approach leverages simple iteration and filtering, keeping the implementation clear and efficient.


Code Solutions

# Define the function to split the words by the separator
def split_words_by_separator(words, separator):
    # Initialize an empty list to store the result.
    result = []
    # Iterate over each word in the input list.
    for word in words:
        # Split the word using the provided separator.
        parts = word.split(separator)
        # Extend the result list with non-empty parts only.
        for part in parts:
            if part:  # Check if the part is not an empty string.
                result.append(part)
    # Return the final list of substrings.
    return result

# Test the function
if __name__ == "__main__":
    # Example test cases
    words1 = ["one.two.three", "four.five", "six"]
    separator1 = "."
    print(split_words_by_separator(words1, separator1))  # Expected: ["one", "two", "three", "four", "five", "six"]

    words2 = ["$easy$", "$problem$"]
    separator2 = "$"
    print(split_words_by_separator(words2, separator2))  # Expected: ["easy", "problem"]

    words3 = ["|||"]
    separator3 = "|"
    print(split_words_by_separator(words3, separator3))  # Expected: []
← Back to All Questions