Length of the Longest Alphabetical Continuous Substring — LeetCode 2414 Python Solution

MediumString
Problem
#2414
Pattern
Hash Map
Reading time
2 min

The problem

An alphabetical continuous string is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string "abcdefghijklmnopqrstuvwxyz".

Example

Input
s = "abacaba"
Output
2
Explanation
There are 4 distinct continuous substrings: "a", "b", "c" and "ab".

Python solution

Python
class Solution:
    def longestContinuousSubstring(self, s: str) -> int:
        ans = cnt = 1
        for x, y in pairwise(map(ord, s)):
            if y - x == 1:
                cnt += 1
                ans = max(ans, cnt)
            else:
                cnt = 1
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string s
SpaceO(1) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2414. Length of the Longest Alphabetical Continuous Substring is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2414. Length of the Longest Alphabetical Continuous Substring?
LeetCode 2414. Length of the Longest Alphabetical Continuous Substring is rated Medium on LeetCode.
What is the time complexity of LeetCode 2414. Length of the Longest Alphabetical Continuous Substring?
The Python solution on this page runs in O(n), where n is the length of the string s.
What is the space complexity of LeetCode 2414. Length of the Longest Alphabetical Continuous Substring?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2414. Length of the Longest Alphabetical Continuous Substring cover?
LeetCode 2414. Length of the Longest Alphabetical Continuous Substring is tagged String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview