Adding Spaces to a String

You are given a 0-indexed string `s` and a 0-indexed integer array `spaces` holding indices of `s`. Insert a space before each character `s[spaces[k]]`, so the space ends up right before that character, and return the modified string. For example, for `s = "EnjoyYourCoffee"` and `spaces = [5, 9]`, spaces go before `"Y"` and `"C"`, giving `"Enjoy Your Coffee"`.

30:00

Adding Spaces to a String
medium
Free written solution
Topics
Companies

You are given a 0-indexed string s and a 0-indexed integer array spaces holding indices of s. Insert a space before each character s[spaces[k]], so the space ends up right before that character, and return the modified string. For example, for s = "EnjoyYourCoffee" and spaces = [5, 9], spaces go before "Y" and "C", giving "Enjoy Your Coffee".

Example 1:
Input: {"s":"LeetcodeHelpsMeLearn","spaces":[8,13,15]}
Output: Leetcode Helps Me Learn
Constraints:
  • 1≤s.length≤3×1051 \leq s.\text{length} \leq 3 \times 10^5

  • s consists only of lowercase and uppercase English letters.

  • 1≤spaces.length≤3×1051 \leq \text{spaces.length} \leq 3 \times 10^5

  • 0≤spaces[i]≤s.length−10 \leq \text{spaces}[i] \leq s.\text{length} - 1

  • All the values of spaces are strictly increasing.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"LeetcodeHelpsMeLearn","spaces":[8,13,15]}

result starts empty. j points at spaces[0] = 8, the next index of s that needs a space in front of it.

spaces, j marks the next cut

8 ◀j
13
15

s, a cut line sits before every index in spaces

L

0

e

1

e

2

t

3

c

4

o

5

d

6

e

7

H

8

e

9

l

10

p

11

s

12

M

13

e

14

L

15

e

16

a

17

r

18

n

19

result, built left to right (0 chars)

(empty)

i = -
j = 0 (spaces[j] = 8)
spaces added = 0
Variables
VariableValue
j0
spaces[j]8
DepthFunction Call
Stack empty
0/25