#2414

Length of the Longest Alphabetical Continuous Substring

Medium
StringTwo PointersSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a single pass through the string to track the current length of an alphabetical substring and update the maximum length found. This is efficient and avoids the overhead of generating all substrings.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize two variables: max_length to 1 and current_length to 1.
  2. 2Step 2: Loop through the string starting from the second character.
  3. 3Step 3: If the current character is consecutive to the previous one, increment current_length.
  4. 4Step 4: If not, reset current_length to 1.
  5. 5Step 5: Update max_length if current_length exceeds it.
solution.py15 lines
1# Full working Python code
2
3def longest_alphabetical_substring(s):
4    max_length = 1
5    current_length = 1
6    for i in range(1, len(s)):
7        if ord(s[i]) == ord(s[i - 1]) + 1:
8            current_length += 1
9        else:
10            current_length = 1
11        max_length = max(max_length, current_length)
12    return max_length
13
14# Example usage
15print(longest_alphabetical_substring('abcde'))  # Output: 5

Complexity note: The time complexity is O(n) because we only make a single pass through the string, where n is the length of the string. The space complexity is O(1) since we are using a constant amount of extra space.

  • 1The longest possible continuous substring can only be up to 26 characters (the entire alphabet).
  • 2Using a single pass through the string is much more efficient than generating all substrings.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.