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 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.

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
Maximum Deletions on a Stringa b a b cOriginal StringababprefixmatchescremainingOperation 1: Delete "ab" → "abc" remainsOperation 2: Delete "abc" → Empty stringMaximum Operations: 2
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
Asked in
Google 15 Facebook 12 Amazon 8
15.0K Views
Medium Frequency
~35 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen