Program to find length of longest consecutively increasing substring in Python


Suppose we have a lowercase string s. This contains English letters as well as "?" Symbol. For each "?" we must either remove it or replace it with any lowercase letter. We have to find the length of the longest consecutively increasing substring that starts with letter "a".

So, if the input is like s = "vta???defke", then the output will be 6, as we can turn s into "vtabcdefke" and "abcdef" is the longest consecutively increasing substring, and this is also starting with "a".

To solve this, we will follow these steps −

  • maxlen := 0
  • length := 0
  • qmarks := 0
  • for each c in s, do
    • if c is same as "?", then
      • qmarks := qmarks + 1
    • otherwise,
      • idx := (ASCII of c) - (ASCII of "a")
      • length := idx + 1 if length <= idx <= length + qmarks or idx <= qmarks otherwise 0
      • qmarks := 0
    • maxlen := maximum of maxlen and (minimum of length + qmarks and 26)
  • return maxlen

Example

Let us see the following implementation to get better understanding −

def solve(s):
   maxlen = length = qmarks = 0
   for c in s:
      if c == "?":
         qmarks += 1
      else:
         idx = ord(c) - ord("a")
         length = idx + 1 if length <= idx <= length + qmarks or idx <= qmarks else 0
         qmarks = 0
      maxlen = max(maxlen, min(length + qmarks, 26))
   return maxlen

s = "vta???defke"
print(solve(s))

Input

"vta???defke"

Output

6

Updated on: 19-Oct-2021

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements