Maximum Deletions on a String - 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
iletters ofsif the firstiletters ofsare equal to the followingiletters ins, for anyiin the range1 <= i <= s.length / 2.
For example, if s = "ababc", then in one operation, you could delete the first two letters of s to get "abc", since the first two letters of s and the following two letters of s are both equal to "ab".
Return the maximum number of operations needed to delete all of s.
Input & Output
Example 1 — Basic Case
$
Input:
s = "ababc"
›
Output:
2
💡 Note:
First operation: delete "ab" (first 2 chars match next 2 chars), leaving "abc". Second operation: delete entire remaining string "abc". Total: 2 operations.
Example 2 — No Matching Prefix
$
Input:
s = "abc"
›
Output:
1
💡 Note:
No matching prefix found ("a" ≠ "b"), so we can only delete the entire string in one operation.
Example 3 — Repeated Pattern
$
Input:
s = "abab"
›
Output:
2
💡 Note:
First operation: delete "ab" (matches next "ab"), leaving "ab". Second operation: delete remaining "ab". Total: 2 operations.
Constraints
- 1 ≤ s.length ≤ 1000
- s consists of only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input String
Given string s = "ababc"
2
Find Matching Prefix
First 2 chars "ab" match next 2 chars "ab"
3
Delete and Repeat
Delete prefix, continue with remaining string
Key Takeaway
🎯 Key Insight: Find matching prefixes to maximize deletion operations rather than deleting the entire string at once
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code