Split Strings by Separator - Problem

Given an array of strings and a character separator, split each string in the array by the separator.

Return an array of strings containing the new strings formed after the splits, excluding empty strings.

Notes:

  • The separator is used to determine where the split should occur, but it is not included as part of the resulting strings.
  • A split may result in more than two strings.
  • The resulting strings must maintain the same order as they were initially given.

Input & Output

Example 1 — Basic Splitting
$ Input: words = ["one.two.three", "four.five", "six"], separator = "."
Output: ["one","two","three","four","five","six"]
💡 Note: Split each string by '.': "one.two.three" becomes ["one","two","three"], "four.five" becomes ["four","five"], "six" has no separator so stays ["six"]
Example 2 — Empty Strings Filtered
$ Input: words = ["$easy$", "$problem$"], separator = "$"
Output: ["easy","problem"]
💡 Note: Split by '$': "$easy$" becomes ["","easy",""], "$problem$" becomes ["","problem",""]. Empty strings are filtered out.
Example 3 — No Separators
$ Input: words = ["hello", "world"], separator = "."
Output: ["hello","world"]
💡 Note: No separators found, so each word remains as a single string in the result

Constraints

  • 1 ≤ words.length ≤ 100
  • 1 ≤ words[i].length ≤ 20
  • characters in words[i] are either lowercase English letters or characters from the string ".,|$#@" (including the separator)
  • separator is a character from the string ".,|$#@"

Visualization

Tap to expand
Split Strings by Separator INPUT words array: "one.two.three" "four.five" "six" separator: "." Dots are separators: one.two.three four.five six (no dots) ALGORITHM STEPS 1 Initialize Result Create empty array 2 Loop Each Word Iterate through words[] 3 Split by Separator Use split(".") function 4 Filter and Add Skip empty, add to result Example Split: "one.two.three" --> ["one","two","three"] "four.five" --> ["four","five"] FINAL RESULT Output array: "one" "two" "three" "four" "five" "six" ["one","two","three", "four","five","six"] OK - 6 strings returned Order Preserved: Original sequence maintained No empty strings included 3 + 2 + 1 = 6 total strings (from 3 input words) Key Insight: The built-in split() function handles all the complexity of finding separators and creating substrings. Simply iterate through each word, split by the separator, filter out empty strings, and concatenate results. Time: O(n * m) where n = words count, m = avg word length | Space: O(total characters) TutorialsPoint - Split Strings by Separator | Built-in Split Function Approach
Asked in
Google 15 Amazon 12 Facebook 8
23.0K Views
Medium Frequency
~10 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen