Adding Spaces to a String

Medium Topics Company Tags

Insert one space immediately before each character whose original zero-based index appears in spaces. All indices refer to the original string s, so earlier insertions do not shift later insertion positions. Return the resulting string. An index of 0 inserts a leading space. The indices are distinct and listed in increasing order.

Example 1:

Input: s = "ReadMoreBooks"
spaces = [4,8]

Output: "Read More Books"

Explanation: The characters at original indices 4 and 8 are M and B. Insert spaces before them to form "Read More Books".

Example 2:

Input: s = "ABC"
spaces = [0,1,2]

Output: " A B C"

Explanation: Insert a space before each character, including the first one. The result is " A B C", with a leading space.

Example 3:

Input: s = "abcd"
spaces = [1,2]

Output: "a b cd"

Explanation: The indices refer to the original string: insert spaces before b and c. The result is "a b cd"; the first insertion does not change which character the second index names.

Constraints:

  • 1 <= s.length <= 300000
  • s contains only lowercase and uppercase English letters.
  • 1 <= spaces.length <= 300000
  • 0 <= spaces[i] < s.length
  • The indices in spaces are strictly increasing.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.