Adding Spaces to a String - Problem
Transform a string by inserting spaces at specific positions!
You are given a string
๐ฏ Goal: Return the modified string with spaces added at the correct positions
๐ฅ Input: A string
๐ค Output: The string with spaces inserted before characters at given indices
Example: Given
You are given a string
s and an array of indices spaces. Your task is to insert spaces before the characters at the specified indices to create a new formatted string.๐ฏ Goal: Return the modified string with spaces added at the correct positions
๐ฅ Input: A string
s and an integer array spaces containing indices๐ค Output: The string with spaces inserted before characters at given indices
Example: Given
s = "EnjoyYourCoffee" and spaces = [5, 9], we insert spaces before index 5 ('Y') and index 9 ('C') to get "Enjoy Your Coffee". Input & Output
example_1.py โ Basic Word Separation
$
Input:
s = "EnjoyYourCoffee"<br>spaces = [5, 9]
โบ
Output:
"Enjoy Your Coffee"
๐ก Note:
We insert spaces before indices 5 ('Y') and 9 ('C'), creating natural word boundaries to form readable text.
example_2.py โ Multiple Small Words
$
Input:
s = "icodeinpython"<br>spaces = [1, 5, 7, 9]
โบ
Output:
"i code in python"
๐ก Note:
Spaces are inserted before indices 1, 5, 7, and 9, transforming a concatenated string into separate words.
example_3.py โ Single Space at Beginning
$
Input:
s = "spacing"<br>spaces = [0]
โบ
Output:
" spacing"
๐ก Note:
A space is inserted at the very beginning (index 0), demonstrating edge case handling for the first position.
Visualization
Tap to expand
Understanding the Visualization
1
Scan Input
Examine the string and note positions marked for space insertion
2
Build Result
Process each character, adding spaces when reaching marked positions
3
Two Pointers
Use one pointer for string position and another for spaces array
4
Final String
Combine all characters and inserted spaces into final result
Key Takeaway
๐ฏ Key Insight: Using two pointers allows us to process the string and space positions simultaneously in optimal O(n + m) time, taking advantage of the sorted spaces array to avoid expensive lookups.
Time & Space Complexity
Time Complexity
O(n + m)
Single pass through string of length n and spaces array of length m
โ Linear Growth
Space Complexity
O(n + m)
Space for result string which will have length n + m
โก Linearithmic Space
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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code