Length of the Longest Alphabetical Continuous Substring - 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".

For example, "abc" is an alphabetical continuous string, while "acb" and "za" are not.

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

Input & Output

Example 1 — Basic Continuous Sequence
$ Input: s = "abacabad"
Output: 2
💡 Note: The longest alphabetical continuous substring is "ab" which has length 2
Example 2 — Multiple Sequences
$ Input: s = "abcde"
Output: 5
💡 Note: The entire string "abcde" is alphabetically continuous with length 5
Example 3 — Single Character
$ Input: s = "a"
Output: 1
💡 Note: Single character strings have alphabetical continuous length of 1

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of only lowercase English letters

Visualization

Tap to expand
Longest Alphabetical Continuous Substring INPUT String s = "abacabad" a 0 b 1 a 2 c 3 a 4 b 5 a 6 d 7 Continuous Substrings: "ab" len=2 "a" len=1 "c" len=1 "ab" len=2 "a" len=1 "d" len=1 Input Values: s = "abacabad" Length: 8 characters ALGORITHM STEPS 1 Initialize maxLen=1, currLen=1 2 Iterate String Loop from index 1 to n-1 3 Check Consecutive If s[i] == s[i-1] + 1 4 Update Counters currLen++ or reset to 1 Execution Trace: i char cons? curr max 0 a -- 1 1 1 b YES 2 2 2 a NO 1 2 3 c NO 1 2 4 a NO 1 2 5 b YES 2 2 6-7 a,d NO 1 2 FINAL RESULT Longest continuous substrings found: a b a c a b a d Orange highlighted = "ab" (length 2) OUTPUT 2 Verification: "ab" at indices [0,1]: OK "ab" at indices [4,5]: OK Max Length = 2 Key Insight: Two characters are consecutive in alphabet if: s[i] - s[i-1] == 1 (ASCII difference) We only need O(1) space by tracking current length and max length while scanning once. Time Complexity: O(n) | Space Complexity: O(1) TutorialsPoint - Length of the Longest Alphabetical Continuous Substring | Optimal Solution
Asked in
Amazon 15 Microsoft 12 Google 8
28.5K Views
Medium Frequency
~15 min Avg. Time
834 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