Length of the Longest Alphabetical Continuous Substring - Problem

Imagine you're reading the alphabet sequence "abcdefghijklmnopqrstuvwxyz" and looking for the longest streak of consecutive letters within a given string.

An alphabetical continuous substring is a sequence of consecutive letters from the alphabet. For example:

  • "abc" ✅ (consecutive: a→b→c)
  • "def" ✅ (consecutive: d→e→f)
  • "acb" ❌ (not consecutive)
  • "za" ❌ (z→a wraps around, not consecutive)

Goal: Given a string s of lowercase letters, find the length of the longest alphabetical continuous substring.

Input: A string s containing only lowercase English letters
Output: An integer representing the maximum length of any alphabetical continuous substring

Input & Output

example_1.py — Basic continuous sequence
$ Input: s = "abcxyz"
Output: 3
💡 Note: The longest alphabetical continuous substrings are "abc" and "xyz", both with length 3. We return 3.
example_2.py — Single character
$ Input: s = "a"
Output: 1
💡 Note: The string contains only one character, so the longest continuous substring has length 1.
example_3.py — No continuous sequences
$ Input: s = "acegik"
Output: 1
💡 Note: No two adjacent characters are consecutive in the alphabet, so the longest continuous substring is any single character with length 1.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of only lowercase English letters
  • Alphabetical continuous means consecutive letters in the alphabet (a→b→c, not a→c→e)

Visualization

Tap to expand
🏃‍♂️ The Alphabet Marathonabib #1bbib #2cbib #3xbib #24Tracking Board👟 Current streak: 3 runners (a→b→c)🏆 Best streak so far: 3 runners⚠️ Next runner 'x' breaks the sequence (gap too big)🔄 Reset counter and continue...💡 Key insight: Only compare adjacent runners - if bib numbers are consecutive, the streak continues!
Understanding the Visualization
1
Start the race
Initialize with first character, set current streak to 1
2
Check next runner
Compare if next character's ASCII is exactly +1 from previous
3
Extend or reset
If consecutive, extend streak; otherwise reset to 1
4
Track best time
Keep updating maximum length throughout the race
Key Takeaway
🎯 Key Insight: We only need to compare adjacent characters - if `char[i] == char[i-1] + 1`, the alphabetical sequence continues. This single comparison per character gives us optimal O(n) performance!
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
28.4K Views
Medium Frequency
~12 min Avg. Time
945 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen