#2430

Maximum Deletions on a String

Hard
StringDynamic ProgrammingRolling HashString MatchingHash FunctionDynamic ProgrammingString Matching
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages dynamic programming to efficiently calculate the maximum deletions by storing results of subproblems. This avoids redundant calculations and significantly reduces the time complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a dp array of size n (length of s) to store the maximum deletions for each prefix.
  2. 2Step 2: Iterate through each character in the string, checking for valid deletions based on the prefix match condition.
  3. 3Step 3: For each valid deletion found, update the dp array to reflect the maximum deletions possible.
solution.py10 lines
1def maxDeletions(s):
2    n = len(s)
3    dp = [0] * n
4    for i in range(n):
5        dp[i] = dp[i - 1] + 1 if i > 0 else 1
6        for j in range(1, (i + 1) // 2 + 1):
7            if s[:j] == s[j:j + j]:
8                dp[i] = max(dp[i], dp[i - j] + 1)
9    return dp[-1]
10

Complexity note: The time complexity is O(n) because we only traverse the string once, and the space complexity is O(n) due to the dp array storing results for each prefix.

  • 1Dynamic programming can significantly reduce redundant calculations.
  • 2Understanding prefix matching is crucial for optimizing deletions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.