Leetcode 2109: Adding Spaces to a String

grid47
grid47
Exploring patterns and algorithms
Apr 10, 2024 5 min read

You are given a string s and an array spaces. The array contains indices where spaces need to be inserted into the string. Each space should be added before the character at the respective index. Return the modified string with the spaces inserted.
Problem
Approach
Steps
Complexity
Input: You are given a string s consisting of lowercase and uppercase English letters and an array spaces where each element is an index at which a space should be inserted.
Example: s = "HelloWorld", spaces = [5]
Constraints:
• 1 <= s.length <= 3 * 10^5
• 1 <= spaces.length <= 3 * 10^5
• 0 <= spaces[i] <= s.length - 1
• The values in spaces are strictly increasing
Output: Return the string with spaces inserted before the characters at the indices specified in the array spaces.
Example: For s = "HelloWorld", spaces = [5], the output should be "Hello World".
Constraints:
Goal: The goal is to modify the string by inserting spaces at the specified indices.
Steps:
• Iterate through the string and check if the current index matches an index from the spaces array.
• If the index matches, insert a space before the current character.
• Continue processing the remaining characters in the string after inserting the spaces.
Goal: The constraints ensure that the function works efficiently even with large inputs.
Steps:
• The string length and the number of indices in spaces can be large (up to 300,000).
Assumptions:
• The input string s only contains English letters.
• The array spaces is sorted and does not contain duplicate values.
Input: Example 1: s = "ProgrammingIsFun", spaces = [11, 14]
Explanation: We insert spaces before 'I' at index 11 and before 'F' at index 14 to obtain the string: "Programming Is Fun".

Input: Example 2: s = "CodingChallenges", spaces = [6, 11]
Explanation: We insert spaces before 'C' at index 6 and before 'C' at index 11 to obtain the string: "Coding Challenges".

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus