Skip to content

2109. Adding Spaces to a String 👍

  • Time: $O(n)$
  • Space: $O(n)$
1
2
3
4
class Solution {
 public:
  string addSpaces(string s, vector<int>& spaces) {}
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public String addSpaces(String s, int[] spaces) {
    StringBuilder sb = new StringBuilder();
    int j = 0; // spaces' index

    for (int i = 0; i < s.length(); ++i) {
      if (j < spaces.length && i == spaces[j]) {
        sb.append(' ');
        ++j;
      }
      sb.append(s.charAt(i));
    }

    return sb.toString();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def addSpaces(self, s: str, spaces: list[int]) -> str:
    ans = []
    j = 0  # spaces' index

    for i, c in enumerate(s):
      if j < len(spaces) and i == spaces[j]:
        ans.append(' ')
        j += 1
      ans.append(c)

    return ''.join(ans)