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 String INPUT String s = "ababc" a 0 b 1 a 2 b 3 c 4 Prefix Matching: "ab" == "ab" First 2 chars = Next 2 chars DP Array: dp[i] = max ops from index i 2 2 1 1 1 dp[0] dp[1] dp[2] dp[3] dp[4] ALGORITHM STEPS 1 Initialize DP Array dp[i] = 1 (can delete whole) 2 Process Right to Left For each position i from n-1 3 Check Prefix Matches If s[i..i+k] == s[i+k..i+2k] 4 Update DP Value dp[i] = max(dp[i], 1+dp[i+k]) Trace for "ababc": Op 1: "ababc" Delete "ab" (prefix match) Op 2: "abc" Delete entire "abc" Total: 2 operations FINAL RESULT Maximum Operations 2 Operation Sequence: Operation 1: "ababc" --> "abc" Operation 2: "abc" --> "" (deleted) Output: 2 [OK] Key Insight: Use DP with string hashing (Z-function or rolling hash) to efficiently check if prefix s[i..i+k] equals s[i+k..i+2k]. Process right-to-left: dp[i] = max(1, 1 + dp[i+k]) for all valid k. Time: O(n^2), Space: O(n). The answer is dp[0] representing max deletions from start. TutorialsPoint - Maximum Deletions on a String | DP Approach
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