VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-number-of-given-operations-to-remove-the-entire-string/

⇱ Maximum number of given operations to remove the entire string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum number of given operations to remove the entire string

Last Updated : 7 Feb, 2023

Given string str containing lowercase English characters, we can perform the following two operations on the given string: 

  1. Remove the entire string.
  2. Remove a prefix of the string str[0...i] only if it is equal to the sub-string str[(i + 1)...(2 * i + 1)].

The task is to find the maximum number of operations required to delete the entire string.

Examples:  

Input: str = "abababab" 
Output:
Explanation: 
Operation 1: Delete prefix "ab" and the string becomes "ababab". 
Operation 2: Delete prefix "ab" and the string becomes "abab". 
Operation 3: Delete prefix "ab", str = "ab". 
Operation 4: Delete the entire string.

Input: s = "abc" 
Output:

Approach using KMP + Dynamic programming:

The idea is to store all possible length deletion of 2nd operation for every index of the given string and explore every possible deletion on each index and return the maximum operation among them.

Follow the step below to implement the above idea:

  • Iterate over all the indexes and find What are the possible deletions using 2nd operation that can be performed starting at index i.
    • Use KMP algorithm to find all such possible deletions.
      • If LPS (longest common prefix which is also a suffix) ending at i  satisfy the condition that the length of substring ending at i is double the length of LPS at i, then this is a possible jump and store it into some array.
  • Iterate over each index and go for every possible length of deletion at index i and maximize the result.

Below is the implementation of the above approach:  


Output
4

Time Complexity: O(N2)
Auxiliary Space: O(N)

Comment