Leetcode #2430: Maximum Deletions on a String
In this guide, we solve Leetcode #2430 Maximum Deletions on a String in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given a string s consisting of only lowercase English letters. In one operation, you can: Delete the entire string s, or Delete the first i letters of s if the first i letters of s are equal to the following i letters in s, for any i in the range 1 <= i <= s.length / 2.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: String, Dynamic Programming, String Matching, Hash Function, Rolling Hash
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: s = "abcabcdabc"
Output: 2
Explanation:
- Delete the first 3 letters ("abc") since the next 3 letters are equal. Now, s = "abcdabc".
- Delete all the letters.
We used 2 operations so return 2. It can be proven that 2 is the maximum number of operations needed.
Note that in the second operation we cannot delete "abc" again because the next occurrence of "abc" does not happen in the next 3 letters.
Python Solution
class Solution:
def deleteString(self, s: str) -> int:
def dfs(i: int) -> int:
if i == n:
return 0
ans = 1
for j in range(1, (n - i) // 2 + 1):
if s[i : i + j] == s[i + j : i + j + j]:
ans = max(ans, 1 + dfs(i + j))
return ans
n = len(s)
return dfs(0)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.