Similar Problems

Similar Problems not available

Adding Spaces To A String - Leetcode Solution


LeetCode:  Adding Spaces To A String Leetcode Solution

Difficulty: Medium

Topics: string two-pointers array simulation  

The problem "Adding Spaces To A String" on LeetCode asks for a function that takes a string of lowercase letters without any spaces, and returns all possible combinations of spaces between the letters. The spaces must be added in such a way that each word in the resulting string is a valid dictionary word.

Here is a detailed solution for this problem:

  1. Create a function that takes the input string and a dictionary of valid words as arguments.
def add_spaces(input_string, dictionary):
  1. Initialize a list results to store all possible combinations of spaces between the letters.
results = []
  1. Create a recursive function helper that takes the input string, a list of valid words built so far, and the current index in the input string as arguments.
def helper(input_string, curr_words, curr_index):
  1. If we have reached the end of the string, check if the current list of words is valid, and if so, append it to the results list.
if curr_index == len(input_string):
    if is_valid(curr_words, dictionary):
        results.append(" ".join(curr_words))
  1. Otherwise, recursively call the helper function by including the current character without a space and a space in the current word.
    curr_char = input_string[curr_index]
    helper(input_string, curr_words + [curr_char], curr_index + 1)
    if curr_words:
        last_word = curr_words[-1]
        curr_words[-1] = last_word + curr_char
        helper(input_string, curr_words[: -1] + [last_word + " " + curr_char], curr_index + 1)
  1. The is_valid function checks if a list of words is valid by checking if each word is present in the dictionary. You can implement this function using a hash set for faster lookups.
def is_valid(word_list, dictionary):
    for word in word_list:
        if word not in dictionary:
            return False
    return True
  1. Finally, call the helper function with the initial arguments and return the results list.
helper(input_string, [], 0)
return results

The time complexity of this solution is O(2^n), where n is the length of the input string, since we are creating all possible combinations of spaces between the characters. The space complexity is also O(2^n), since the results list can potentially contain all possible combinations. However, in practice, the space complexity may be lower, since many combinations may not be valid words and can be pruned early.

Adding Spaces To A String Solution Code