algoadvance

Leetcode 2788. Split Strings by Separator

Problem Statement

Given an array of strings words and a character separator, split each string in words by the separator and return all split substrings in the form of a flat list.

Constraints:

Clarifying Questions

  1. Input format:
    • Can the separator be an empty string?
      • No, assume it’s always a single character.
    • Will there be any empty strings within the input words array?
      • It might be possible.
  2. Edge Cases:
    • What if a string in words contains only the separator?
      • The resulting substrings for that string should be empty.
    • Should the output include empty substrings that result from consecutive separators?
      • Yes, they should be included.

Strategy

  1. Initialize an empty list to store the substrings.
  2. Iterate through each string in words.
  3. For each string, split it using the given separator.
  4. Add all the resulting substrings to the list.
  5. Return the flattened list of substrings.

Code

import java.util.ArrayList;
import java.util.List;

public class SplitStringsBySeparator {
    
    public static List<String> splitWordsBySeparator(String[] words, char separator) {
        List<String> result = new ArrayList<>();
        
        for (String word : words) {
            String[] splitParts = word.split(Character.toString(separator));
            for (String part : splitParts) {
                result.add(part);
            }
        }
        
        return result;
    }
    
    public static void main(String[] args) {
        String[] words = {"hello.world", "java.is,fun", "split;by;separator"};
        char separator = '.';
        System.out.println(splitWordsBySeparator(words, separator));
        
        separator = ',';
        System.out.println(splitWordsBySeparator(words, separator));

        separator = ';';
        System.out.println(splitWordsBySeparator(words, separator));
    }
}

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI