Skip to content

2109. Adding Spaces to a String #907

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We can use an efficient approach with two pointers. Here's how the implementation in PHP 5.6 would look:

Solution Explanation:

  1. Use a pointer spaceIndex to track the current position in the spaces array.
  2. Iterate through the string s using a loop.
  3. Check whether the current index in the string matches the current value in the spaces array. If it does, append a space to the result and move the spaceIndex pointer forward.
  4. Append the current character of the string to the result.
  5. Return the final result as a single string.

This approach ensures that we process the input efficiently, taking advantage of the sorted order of the spaces array.

Let's implement this solution in PHP: 2109. Adding Sp…

Replies: 1 comment 2 replies

Comment options

mah-shamim
Dec 3, 2024
Maintainer Author

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Dec 3, 2024
Collaborator

@mah-shamim
Comment options

mah-shamim Dec 3, 2024
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants