⚡Flashcard Drill➔
NeetCode #212LC-1750MediumTwo Pointers
← Back to All Problems

#212 · #1750 · Minimum Length of String After Deleting Similar Ends(删除字符串两端相同字符后的最短长度)

📌 Problem Statement & Constraints

Given a string s consisting only of characters a, b and c, repeatedly delete a prefix and a suffix that both consist of the same character, until no such pair exists. Return the minimum length of the remaining string. Constraints: 1 <= s.length <= 10^5.

💡 Core Algorithmic Approaches

  1. Two pointers at the ends. While the end characters match, greedily consume the entire run of that character from both ends.
  2. Each iteration removes a maximal prefix run and a maximal suffix run of the same character.
  3. The pointers meet or cross when no further deletion is possible, and the remaining length is r - l + 1.
  4. Consuming maximal runs (rather than one character at a time) is what makes the algorithm O(n) rather than O(n^2).

💻 Benchmark Python3 Implementation

class Solution:
    def minimumLength(self, s: str) -> int:
        l, r = 0, len(s) - 1
        while l < r and s[l] == s[r]:
            ch = s[l]
            while l <= r and s[l] == ch:   # consume the whole prefix run
                l += 1
            while l <= r and s[r] == ch:   # consume the whole suffix run
                r -= 1
        return r - l + 1

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each character is consumed at most once.
💾 Space Complexity
O(1): two indices.

⚠️ Interview Pitfalls & Follow-ups

  • Deleting one character from each side per iteration: O(n^2) in the worst case; consume maximal runs instead.
  • Using l < r as the inner loop condition: the runs may overlap, so the guard must be l <= r to avoid over-consuming.
  • Forgetting the outer s[l] == s[r] check: without it, unrelated end characters would be consumed.
  • Returning r - l: the remaining length is r - l + 1, and it can be 0 when the pointers cross.
⚡
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

中文速览与面试要点

删除字符串两端相同字符后的最短长度

给你一个只包含字符 a 、 b 和 c 的字符串 s,你可以执行下面这个操作(5 个步骤)任意次:① 选择字符串 s 一个 非空 的前缀,这个前缀的所有字符都相同;② 选择字符串 s 一个 非空 的后缀,这个后缀的所有字符都相同;③ 前缀和后缀在字符串中任意位置都 不能有交集 ;④ 前缀和后缀包含的所有字符 相同 ;⑤ 将前缀和后缀都删除。请你返回对字符串 s 执行上面操作任意次以后(可能 0 次),能得到的 最短 长度。约束:1 ≤ s.length ≤ 10^5;s 只包含字符 a 、 b 和 c 。

核心要点

  • 相向双指针贪心删除(标准解) :l 指向左端、r 指向右端。若 s[l] == s[r] ,则把两端所有等于该字符的字符全部删除(l 右移、r 左移),然后重复。
  • 为什么贪心最优 :每次操作都必须删除「两端相同字符的极大连续段」,而删除越多越短;因此只要两端字符相同就应尽可能多地删除。
  • 终止条件 : l &gt;= r (字符串已被删空或只剩一个字符),或 s[l] != s[r] (无法再操作)。
  • 答案 : r − l + 1 (剩余长度)。

常见陷阱

  • 每次只删一个字符 :会得到错误结果。题目允许选择「任意长度的同字符前缀/后缀」,因此应一次删光该字符的所有连续出现。
  • 内层 while 忘记 l &lt;= r 条件 :当字符串全为同一字符时(如 "aaa" ),l 会越过 r,导致越界或错误结果。
  • 外层条件写成 l &lt; r 后忘记处理剩余 :返回 r - l + 1 时,若字符串已被删空则 l = r + 1,得到 0,正确;若剩一个字符则得到 1。
  • 误以为可以不删完 :贪心要求「只要两端相同就删」,删得越多结果越短。

参考实现

class Solution:
    def minimumLength(self, s: str) -> int:
        l, r = 0, len(s) - 1
        while l < r and s[l] == s[r]:
            c = s[l]
            while l <= r and s[l] == c:      # 删除左侧所有 c
                l += 1
            while l <= r and s[r] == c:      # 删除右侧所有 c
                r -= 1
        return r - l + 1                     # 剩余长度(可能为 0)