⚡Flashcard Drill➔
NeetCode #195LC-2109MediumTwo Pointers
← Back to All Problems

#195 · #2109 · Adding Spaces to a String(向字符串添加空格)

📌 Problem Statement & Constraints

You are given a 0-indexed string s and a 0-indexed integer array spaces listing the indices at which spaces should be inserted. Return the resulting string. The indices are strictly increasing. Constraints: 1 <= s.length <= 3 * 10^5, 0 <= spaces[i] < s.length.

💡 Core Algorithmic Approaches

  1. Walk the string with a pointer into spaces. Before emitting each character, insert a space for every index in spaces equal to the current position.
  2. Because the indices are strictly increasing, a single forward pass suffices -- no lookahead or re-scanning is needed.
  3. Building a list and joining avoids repeated string concatenation.
  4. Inserting spaces by rebuilding the string with slices would be O(n * k) because of repeated copies.

💻 Benchmark Python3 Implementation

class Solution:
    def addSpaces(self, s: str, spaces: List[int]) -> str:
        res = []
        sp = 0
        for i, ch in enumerate(s):
            while sp < len(spaces) and spaces[sp] == i:
                res.append(" ")        # insert before position i
                sp += 1
            res.append(ch)
        return "".join(res)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n + k): each character and each space is emitted once.
💾 Space Complexity
O(n + k) for the result.

⚠️ Interview Pitfalls & Follow-ups

  • Rebuilding with s[:i] + " " + s[i:] in a loop: each rebuild is O(n), giving O(n * k).
  • Not exploiting the strictly increasing order of spaces: a pointer is all that is needed; sorting or searching is wasted work.
  • Inserting spaces after the character: the insertion index refers to the position before the character at that index.
  • Using spaces[sp] <= i: with strictly increasing indices and a single pass, equality is the correct test, and using <= would be harmless but misleading.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Two Pointers Problems

中文速览与面试要点

向字符串添加空格

给你一个下标从 0 开始的字符串 s,以及一个下标从 0 开始的整数数组 spaces。数组 spaces 描述原字符串中需要插入空格的 位置 (下标)。在插入空格后,各个空格需要在 spaces 中对应下标的位置上。返回插入空格后的字符串。注意 spaces 按 升序 排列。约束:1 ≤ s.length ≤ 3 × 10^5;1 ≤ spaces.length ≤ 3 × 10^5;0 ≤ spaces[i] &lt; s.length;spaces 严格递增。

核心要点

  • 按空格位置切段拼接(标准解) :维护上一个切分位置 prev ,遍历 spaces 中每个位置 p,取出 s[prev:p] 加入结果,更新 prev = p ;最后补上 s[prev:] ,用空格连接。
  • 为什么不用逐个字符插入 :字符串不可变,逐个插入是 O(n²)。切段 + join 是 O(n)。
  • 为什么直接切段就正确 :spaces 严格递增,因此各段互不重叠且顺序正确, " ".join(...) 会在段间插入空格,恰好对应 spaces 指定的位置。
  • 复杂度 :O(n) 时间,O(n) 空间。

常见陷阱

  • 用 s = s[:p] + " " + s[p:] 逐个插入 :每次都是 O(n),整体 O(n · k),在 3 × 10^5 规模下必然超时。
  • 忘记追加最后一段 :循环只处理了 spaces 之前的段,最后一段( s[prev:] )必须单独追加。
  • 用 "".join 而非 " ".join :会丢失空格。
  • 误以为 spaces 可能无序 :题目保证严格递增,因此无需排序。

参考实现

class Solution:
    def addSpaces(self, s: str, spaces: list[int]) -> str:
        res = []
        prev = 0
        for p in spaces:
            res.append(s[prev:p])       # 取出这一段
            prev = p
        res.append(s[prev:])            # 最后一段
        return ' '.join(res)            # 段间用空格连接