Adding Spaces to a String — LeetCode 2109 Python Solution

MediumArrayTwo PointersStringSimulation
Problem
#2109
Reading time
2 min

The problem

You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index.

Example

Input
s = "LeetcodeHelpsMeLearn", spaces = [8,13,15]
Output
"Leetcode Helps Me Learn"
Explanation
The indices 8, 13, and 15 correspond to the underlined characters in "LeetcodeHelpsMeLearn".

Python solution

Python
class Solution:
    def addSpaces(self, s: str, spaces: List[int]) -> str:
        ans = []
        j = 0
        for i, c in enumerate(s):
            if j < len(spaces) and i == spaces[j]:
                ans.append(' ')
                j += 1
            ans.append(c)
        return ''.join(ans)

Complexity

MeasureComplexity
TimeO(n + m)
SpaceO(n + m), where n and m are the lengths of the string s and the array spaces, respectively auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2109. Adding Spaces to a String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2109. Adding Spaces to a String?
LeetCode 2109. Adding Spaces to a String is rated Medium on LeetCode.
What is the time complexity of LeetCode 2109. Adding Spaces to a String?
The Python solution on this page runs in O(n + m).
What is the space complexity of LeetCode 2109. Adding Spaces to a String?
The Python solution on this page uses O(n + m), where n and m are the lengths of the string s and the array spaces, respectively auxiliary space.
What topics does LeetCode 2109. Adding Spaces to a String cover?
LeetCode 2109. Adding Spaces to a String is tagged Array, Two Pointers, String and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview