DDSA Solutions

2109. Adding Spaces to a String

Time: O(n)
Space: O(n)
Advertisement

Intuition

Add spaces at given indices in a string. Build result character by character, inserting spaces at specified positions.

Algorithm

  1. 1Two pointers: string index and spaces index. Append char; if current index is in spaces array, append space first.

Common Pitfalls

  • Spaces are inserted BEFORE the character at given index. Indices are in the original string.
2109.cs
C#
// Approach: Two-pointer over s and spaces array; insert space at each specified index.
// Time: O(n) Space: O(n)

public class Solution
{
    public string AddSpaces(string s, int[] spaces)
    {
        StringBuilder sb = new StringBuilder();
        int j = 0; // spaces' index

        for (int i = 0; i < s.Length; ++i)
        {
            if (j < spaces.Length && i == spaces[j])
            {
                sb.Append(' ');
                ++j;
            }
            sb.Append(s[i]);
        }

        return sb.ToString();
    }
}
Advertisement
Was this solution helpful?