The Indian Engineer

Problem 2109 Adding Spaces to a String

Posted on 6 mins

Array Two-Pointers String Simulation

Problem Statement

Link - Problem 2109

Question

You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index.

Return the modified string after the spaces have been added.

Example 1:

Input: s = "LeetcodeHelpsMeLearn", spaces = [8,13,15]
Output: "Leetcode Helps Me Learn"
Explanation: 
The indices 8, 13, and 15 correspond to the underlined characters in "LeetcodeHelpsMeLearn".
We then place spaces before those characters.

Example 2:

Input: s = "icodeinpython", spaces = [1,5,7,9]
Output: "i code in py thon"
Explanation:
The indices 1, 5, 7, and 9 correspond to the underlined characters in "icodeinpython".
We then place spaces before those characters.

Example 3:

Input: s = "spacing", spaces = [0,1,2,3,4,5,6]
Output: " s p a c i n g"
Explanation:
We are also able to place spaces before the first character of the string.

Constraints:

Solution

class Solution {
public:
    string addSpaces(string s, vector<int>& spaces) {
        int total_size = s.size() + spaces.size();
        char result[total_size];
        int s_index = 0, spaces_index = 0, res_index = 0;

        while (s_index < s.size()) {
            if (spaces_index < spaces.size() && s_index == spaces[spaces_index]) {
                result[res_index++] = ' ';
                spaces_index++;
            }
            result[res_index++] = s[s_index++];
        }
        return string(result, total_size);
    }
};

Complexity Analysis

| Algorithm                                           | Time Complexity | Space Complexity |
| --------------------------------------------------- | --------------- | ---------------- |
| Modified two-pointer traversal for string insertion | O(n)            | O(n)             |

Explanation

Intial Thoughts

Think of the original string as a straight line without any spaces. The spaces array represents specific points where you want to introduce spaces. A natural approach could be to start from the beginning of the string and move through each character while also keeping track of the spaces we have to add. Another possible way could be to think of it as a sorting problem where you combine all the characters and spaces together in the correct order.

Intuitive Analysis

Intuitively, it feels like a two-pointer problem where you’re tracking both the current character in the string and the current space you need to add. The key insight is that you don’t actually need to physically separate these two lists – you can generate the resulting string on the fly by deciding whether to add a space or a character at each step. This results in a very efficient and clean solution without the need for explicit loops or extra memory allocations beyond what’s needed.

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Medium difficulty.

Hints

Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character.

Since the array of indices for the space locations is sorted, use a pointer to keep track of the next index to place a space. Only increment the pointer once a space has been appended.

Ensure that your append operation can be done in O(1).