Program to find minimum number of monotonous string groups in Python

Suppose we have a lowercase string s. We need to find the minimum number of contiguous substrings that s can be divided into, where each substring is either non-increasing (monotonically decreasing) or non-decreasing (monotonically increasing).

For example, "pqqqr" is a non-decreasing string, and "qqqp" is a non-increasing string.

Problem Example

If the input is s = "pqrsrqp", then the output will be 2, because we can break s into "pqrs" (non-decreasing) and "rqp" (non-increasing).

Algorithm Steps

To solve this problem, we follow these steps ?

  • If string is empty, return 0
  • Initialize variables: last character, direction tracker, and count
  • Iterate through each character and track direction changes
  • When direction changes from increasing to decreasing (or vice versa), increment count
  • Return the total count of monotonous groups

Direction Tracking Logic

We use direction codes ?

  • 1: Initial state (no direction determined yet)
  • 0: Non-decreasing (increasing or equal)
  • 2: Non-increasing (decreasing)

Implementation

def solve(s):
    if not s:
        return 0

    last = s[0]
    direction = 1  # 1: initial, 0: non-decreasing, 2: non-increasing
    count = 1

    for char in s:
        if char > last:
            if direction == 1:
                direction = 0  # Set to non-decreasing
            elif direction == 2:
                direction = 1  # Reset and start new group
                count += 1
        elif char < last:
            if direction == 1:
                direction = 2  # Set to non-increasing
            elif direction == 0:
                direction = 1  # Reset and start new group
                count += 1
        last = char

    return count

# Test the function
s = "pqrsrqp"
result = solve(s)
print(f"Input: {s}")
print(f"Minimum monotonous groups: {result}")
Input: pqrsrqp
Minimum monotonous groups: 2

Step-by-Step Trace

For input "pqrsrqp", let's trace the algorithm ?

Character Comparison Direction Count Group
p - 1 (initial) 1 pqrs...
q q > p 0 (non-decreasing) 1 pqrs...
r r > q 0 (continues) 1 pqrs
s s > r 0 (continues) 1 pqrs
r r 1 (reset) 2 rqp
q q 2 (non-increasing) 2 rqp
p p 2 (continues) 2 rqp

Additional Example

# Test with different strings
test_cases = ["abcde", "edcba", "abcba", "aabbc"]

for s in test_cases:
    result = solve(s)
    print(f"'{s}' requires {result} monotonous group(s)")
'abcde' requires 1 monotonous group(s)
'edcba' requires 1 monotonous group(s)
'abcba' requires 2 monotonous group(s)
'aabbc' requires 1 monotonous group(s)

Conclusion

This algorithm efficiently finds the minimum number of monotonous groups by tracking direction changes in a single pass. The time complexity is O(n) and space complexity is O(1), making it optimal for this problem.

Updated on: 2026-03-26T15:52:38+05:30

439 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements