VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-splits-to-generate-monotonous-substrings-from-given-string/

⇱ Minimize splits to generate monotonous Substrings from given String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimize splits to generate monotonous Substrings from given String

Last Updated : 19 May, 2021

Given a string str, the task is to find the minimum numbers of substrings that the given string S can be split into, such that each substring is monotonously increasing or decreasing.

Examples:

Input: str = "abcdcba" 
Output:
Explanation: 
The string can be split into a minimum of 2 monotonous substrings {"abcd"(increasing), "cba"(decreasing)}
Input: str = "aeccdhba" 
Output:
Explanation: 
The generated substrings are {"ae", "ccdh", "ba"}

Approach: Follow the steps below to solve the problem:

  • Initialize a variable ongoing = 'N' to keep track of order of current sequence.
  • Iterate over the string and for each character, follow the steps below:
  • If ongoing == 'N'
    • If curr_character < prev_character then update ongoing with D(Non-Increasing).
    • Otherwise, if curr_character > prev_character, then update ongoing with I(Non-Decreasing).
    • Otherwise, update ongoing with N(neither Non-Increasing nor Non-Decreasing).
  • Otherwise, if ongoing == 'I':
    • If curr_character > prev_character then update ongoing with I.
    • Otherwise, if curr_character < prev_character then update ongoing with N and increment answer.
    • Otherwise, update ongoing with I.
  • else  do the following steps:
    • If curr_character < prev_character then update ongoing with D.
    • Otherwise, if curr_character > prev_character then update ongoing with N and increment answer.
    • Otherwise, update ongoing with D.
  • Finally, print answer+1 is the required answer.

Below is the implementation of the above approach:


Output: 
3

 

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

Comment