Maximum Deletions on a String — LeetCode 2430 Python Solution
- Problem
- #2430
- Pattern
- Dynamic Programming
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- s = "abcabcdabc"
- Output
- 2
- Explanation
- - Delete the first 3 letters ("abc") since the next 3 letters are equal. Now, s = "abcdabc".
Python solution
class Solution:
def deleteString(self, s: str) -> int:
@cache
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
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n^2) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2430. Maximum Deletions on a String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2430. Maximum Deletions on a String?
- LeetCode 2430. Maximum Deletions on a String is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2430. Maximum Deletions on a String?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 2430. Maximum Deletions on a String?
- The Python solution on this page uses O(n^2) auxiliary space.
- What topics does LeetCode 2430. Maximum Deletions on a String cover?
- LeetCode 2430. Maximum Deletions on a String is tagged String, Dynamic Programming, String Matching, Hash Function and Rolling Hash on LeetCode.