Problem Description
Given a string s and an array spaces, insert a space before each character in s at the indices specified in spaces. Return the modified string after all the spaces have been added.
Key Insights
- Use the fact that spaces is sorted in strictly increasing order.
- Traverse the string with a pointer while using another pointer (or index) to track the current space index.
- Insert a space into the result string every time the current string index matches the next index in the spaces array.
- Efficiently build the result string ensuring minimal additional space overhead.
Space and Time Complexity
Time Complexity: O(n) where n is the length of s, because each character is processed once. Space Complexity: O(n) to store the final resulting string.
Solution
We use two pointers: one for iterating through the string and one for the spaces array. At each step, if the current index equals the next space index, we append a space before appending the character. This process continues until the end of the string is reached. The sorted nature of the spaces array enables efficient linear traversal.