We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Length of the Longest Alphabetical Continuous Substring

Difficulty: Medium


Problem Description

Given a string s consisting of lowercase letters only, return the length of the longest alphabetical continuous substring.


Key Insights

  • An alphabetical continuous substring consists of consecutive letters in the alphabet.
  • We can iterate through the string while comparing each character with the previous one.
  • If the current character is the next consecutive letter after the previous character, we extend the current substring length.
  • If not, we reset the current substring length.
  • The maximum length encountered during the iteration will be our result.

Space and Time Complexity

Time Complexity: O(n)
Space Complexity: O(1)


Solution

To solve this problem, we will use a simple linear scan through the string. We will maintain two variables: one for the current length of the alphabetical substring and another for the maximum length found. As we iterate through the string, we will check if the current character is the consecutive letter of the previous character. If it is, we increment the current length; otherwise, we reset it to 1. Finally, we will compare the current length with the maximum length found so far and update it accordingly.


Code Solutions

def longestContinuousSubstring(s: str) -> int:
    max_length = 1  # To store the maximum length found
    current_length = 1  # To store the current length of a continuous substring

    # Iterate through the string starting from the second character
    for i in range(1, len(s)):
        # Check if the current character is consecutive to the previous one
        if ord(s[i]) == ord(s[i - 1]) + 1:
            current_length += 1  # Increase the current length
        else:
            current_length = 1  # Reset current length

        max_length = max(max_length, current_length)  # Update max_length if needed

    return max_length
← Back to All Questions