Adding Spaces to a String (LeetCode 2109): Solution and Explanation
Given a string s and a sorted array of indices, put a space in front of each listed character of s and return the new string.
Intuition
The obvious approach inserts one space at a time into the string. Every insert shifts all later characters, so with k spaces on a long string the cost grows to O(n * k).
Building a fresh output avoids the shifting. Each character of s is copied once, and each space is written once, at the moment the copy reaches its index.
The array spaces is strictly increasing, so the copy loop never needs to search it. A second pointer j sits on the next unused entry, and only spaces[j] can ever equal the current index i.
When spaces[j] == i, write a space and move j on, then copy s[i]. When the loop ends every entry of spaces has been used exactly once.
Approach: Two pointers with a string builder
- Create an empty list (or string builder)
resultand setj = 0. - For each index
iofs: ifj < len(spaces)andspaces[j] == i, append a space and incrementj. - Append
s[i]. - Join
resultinto a string and return it.
Step-by-step example
s = "LeetcodeHelpsMeLearn", spaces = [8, 13, 15]
- j = 0 points at spaces[0] = 8. Indices 0 to 7 do not equal 8, so "Leetcode" is copied as is.
- At i = 8, spaces[0] == 8, so a space is written, j becomes 1, then 'H' is copied.
- Indices 9 to 12 copy "elps". At i = 13, spaces[1] == 13, so a space goes in before 'M' and j becomes 2.
- At i = 15, spaces[2] == 15, so a space goes in before 'L' and j becomes 3. No cuts are left.
- The rest of "Learn" is copied, and the result is "Leetcode Helps Me Learn".
Code: Python, Java, C++
1class Solution:
2 def addSpaces(self, s: str, spaces: List[int]) -> str:
3 result = []
4 j = 0
5 for i, ch in enumerate(s):
6 if j < len(spaces) and spaces[j] == i:
7 result.append(" ")
8 j += 1
9 result.append(ch)
10 return "".join(result)1class Solution {
2 public String addSpaces(String s, int[] spaces) {
3 StringBuilder result = new StringBuilder(s.length() + spaces.length);
4 int j = 0;
5 for (int i = 0; i < s.length(); i++) {
6 if (j < spaces.length && spaces[j] == i) {
7 result.append(' ');
8 j++;
9 }
10 result.append(s.charAt(i));
11 }
12 return result.toString();
13 }
14}1class Solution {
2public:
3 string addSpaces(string s, vector<int>& spaces) {
4 string result;
5 result.reserve(s.size() + spaces.size());
6 int j = 0;
7 for (int i = 0; i < (int)s.size(); i++) {
8 if (j < (int)spaces.size() && spaces[j] == i) {
9 result += ' ';
10 j++;
11 }
12 result += s[i];
13 }
14 return result;
15 }
16};Time and space complexity
O(n + k)
Each of the n characters is appended once and each of the k spaces is appended once; the final join is linear in the output length.
O(n + k)
The output itself has n + k characters. Apart from it, only the pointer j is stored.
Other approaches
Insert spaces into the string (time O(n * k), space O(n + k))
Call insert (or slice and concatenate) once per entry of spaces, adjusting each later index by the number of spaces already added. It is short but every insert shifts the tail of the string.
Copy slices between cuts (time O(n + k), space O(n + k))
Append s[prev:spaces[j]] followed by a space for each cut, then the final tail. It does the same work as the character loop with fewer append calls.
Common mistakes
- Inserting into the original string while also reading original indices from spaces. After the first insert every later index is off by the number of spaces already added.
- Checking
spaces[j]without first checkingj < len(spaces), which reads past the end once all cuts are used. - Putting the space after s[i] instead of before it. The space belongs in front of the character at the listed index.
- Building the answer with repeated string concatenation in a language where strings are immutable, which can turn the loop quadratic.
Frequently asked questions
Can spaces contain 0?
Yes. Then the answer starts with a space, because a space is written before s[0].
Why is it enough to look only at spaces[j]?
spaces is strictly increasing and i only grows, so once spaces[j] has been used every later entry is larger than the current i. The next one that can match is always spaces[j].
Is this really a two-pointer problem?
Yes. One pointer walks s and the other walks spaces, and both only move forward, so together they make one linear pass.