Leetcode # 2109. Adding Spaces to a String
- 2024.12.05
- ★★ Medium LeetCode Two Pointers
Problem
https://leetcode.com/problems/adding-spaces-to-a-string
Solution
Time Complexity: O(len(s) + len(spaces))
Space Complexity: O(len(s) + len(spaces))
(The input and output generally do not count towards the space complexity.)
class Solution:
def addSpaces(self, s: str, spaces: List[int]) -> str:
ps = pm = 0
modified_s = [""] * (len(s) + len(spaces))
for i, c in enumerate(s):
if ps < len(spaces) and i == spaces[ps]:
modified_s[pm] = " "
ps += 1
pm += 1
modified_s[pm] = c
pm += 1
return "".join(modified_s)
Last Updated on 2024/12/05 by A1go