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 String: Problem OverviewStep 1: Inputs = "EnjoyYourCoffee"spaces = [5, 9]Original stringInsert positionsStep 2: ProcessIndex 5: Insert space before 'Y'Index 9: Insert space before 'C'Step 3: Output"Enjoy Your Coffee"Result with spacesEfficient: O(n + m) time using two pointers
Understanding the Visualization
1
Input Analysis
Original string and array of space positions
2
Space Insertion
Insert spaces before characters at given indices
3
Output
Modified string with spaces added
Key Takeaway
🎯 Key Insight: Use two pointers to traverse the string and space positions simultaneously for efficient single-pass construction
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