Adding Spaces to a String - Problem

You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index.

For example, given s = "EnjoyYourCoffee" and spaces = [5, 9], we place spaces before 'Y' and 'C', which are at indices 5 and 9 respectively. Thus, we obtain "Enjoy Your Coffee".

Return the modified string after the spaces have been added.

Input & Output

Example 1 — Basic Case
$ Input: s = "EnjoyYourCoffee", spaces = [5,9]
Output: "Enjoy Your Coffee"
💡 Note: Insert space before index 5 (character 'Y') and index 9 (character 'C') to get "Enjoy Your Coffee"
Example 2 — Multiple Spaces
$ Input: s = "icodeinpython", spaces = [1,5,7,9]
Output: "i code in py thon"
💡 Note: Insert spaces at positions 1, 5, 7, and 9 to separate the string into readable segments
Example 3 — Single Space
$ Input: s = "spacing", spaces = [0]
Output: " spacing"
💡 Note: Insert space at the beginning (index 0) to get " spacing"

Constraints

  • 1 ≤ s.length ≤ 3 × 104
  • s consists only of lowercase and uppercase English letters.
  • 1 ≤ spaces.length ≤ 3 × 104
  • 0 ≤ spaces[i] ≤ s.length - 1
  • All the values of spaces are strictly increasing.

Visualization

Tap to expand
Adding Spaces to a String INPUT Original String s: E n j o y Y o u r C o f f e e Indices: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Spaces Array: 5 9 Insert space BEFORE index 5 (Y) and 9 (C) Input Values: s = "EnjoyYourCoffee" spaces = [5, 9] ALGORITHM STEPS 1 Initialize Create result StringBuilder spaceIdx = 0 2 Iterate String Loop through each char at index i (0 to n-1) 3 Check Space Index If i == spaces[spaceIdx]: - Add space to result - Increment spaceIdx 4 Append Character Add current char s[i] to result string Complexity: Time: O(n) - single pass Space: O(n) - result string FINAL RESULT Modified String with Spaces: E n j o y _ Y o u r _ C o f f e e = Inserted Space Insertion Trace: i=0-4: "Enjoy" i=5: spaces[0]=5, add " " i=5-8: "Your" i=9: spaces[1]=9, add " " i=9-14: "Coffee" Output: "Enjoy Your Coffee" OK - 2 spaces inserted Key Insight: Process the string left-to-right with a pointer tracking the next space position. When current index matches spaces[spaceIdx], insert a space BEFORE the character, then move to the next space index. This ensures O(n) time with a single traversal. TutorialsPoint - Adding Spaces to a String | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
25.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen