Adding Spaces to a String

medium string two pointers

Problem

You are given a string s and a strictly increasing array spaces holding character positions. For every index in spaces, place a single space immediately before the character that currently sits at that index in the original string. Return the resulting string. Each value in spaces counts characters of the original s, so earlier insertions do not shift later targets.

Inputs = "ICodeInPython", spaces = [1, 5, 7]
Output"I Code In Python"
Spaces go before s[1]='C', s[5]='I', and s[7]='P', splitting the text into "I", "Code", "In", "Python".

def add_spaces(s, spaces):
    out = []
    p = 0
    for i, ch in enumerate(s):
        if p < len(spaces) and spaces[p] == i:
            out.append(' ')
            p += 1
        out.append(ch)
    return ''.join(out)
function addSpaces(s, spaces) {
  const out = [];
  let p = 0;
  for (let i = 0; i < s.length; i++) {
    if (p < spaces.length && spaces[p] === i) {
      out.push(' ');
      p++;
    }
    out.push(s[i]);
  }
  return out.join('');
}
class Solution {
    public String addSpaces(String s, int[] spaces) {
        StringBuilder out = new StringBuilder();
        int p = 0;
        for (int i = 0; i < s.length(); i++) {
            if (p < spaces.length && spaces[p] == i) {
                out.append(' ');
                p++;
            }
            out.append(s.charAt(i));
        }
        return out.toString();
    }
}
string addSpaces(string s, vector<int>& spaces) {
    string out;
    int p = 0;
    for (int i = 0; i < (int)s.size(); i++) {
        if (p < (int)spaces.size() && spaces[p] == i) {
            out.push_back(' ');
            p++;
        }
        out.push_back(s[i]);
    }
    return out;
}
Time: O(n + m) Space: O(n + m)