Widest Alphabetic Boundary Gap Across Tokens
StringsAuto-graded · 22 test casesLast updated
Tests string scanning, ASCII letter detection, and single-pass maximum tracking with tie handling across whitespace-delimited tokens.
Implement a function max_alpha_gap(text: str) that receives a single text string and reports the widest alphabetic boundary gap found in any of its words, together with every word that attains that gap.
Tokenization. A word is a maximal run of non-whitespace characters, exactly as produced by splitting the text on whitespace (text.split()). Punctuation, digits, and other symbols never break a token: can't and well-known are each one word, and (x) is one word.
Letters. Only the ASCII letters a–z and A–Z count as letters. Any other character (digits, punctuation, and non-ASCII letters such as é) is ignored when locating boundaries.
Gap of a word. Look at the first ASCII letter of the token and the last ASCII letter of the token, ignoring all non-letters in between and at the ends. Map each of those two letters to its position in a=0, b=1, ..., z=25 (case is irrelevant) and take the absolute difference. A word whose first and last letters coincide has gap 0. The direction does not matter: wood (w→d) and dew (d→w) both have gap 19.
Result. Return a tuple (max_gap, words) where:
max_gapis the largest gap over all tokens that contain at least one ASCII letter;wordsis the list of tokens achievingmax_gap, listed in the order they appear in the text, keeping their original surface form — capitalization and any punctuation are preserved exactly as they occur (for example,cannot.is returned ascannot., andCan't!is returned asCan't!);- every occurrence is listed, so a token that appears more than once appears in
wordsmore than once.
Empty case. If the text contains no token with an ASCII letter (for example "", "123 !!! --"), return (0, []).
Constraints
textmay be empty and may contain any printable characters, tabs, and newlines.- The length of
textis at most 100,000 characters. - The result list may contain up to O(n) tokens, where n is the length of
text.
Examples
Example 1
Input: max_alpha_gap('cab pat Float wood would I pop')
Output: [19, ['wood', 'would']]
Example 2
Input: max_alpha_gap('can\'t cannot.')
Output: [17, ['can\'t', 'cannot.']]
Example 3
Input: max_alpha_gap('The quick brown fox jumps over the lazy dog.')
Output: [18, ['fox']]
Example 4
Input: max_alpha_gap('123 !!! --')
Output: [0, []]
Hints
Hint 1
A word's gap depends only on its first and last ASCII letters; everything in between is irrelevant.
Hint 2
Use `str.split()` for whitespace tokenization and scan each token character by character to locate its two boundary letters.
Hint 3
Keep a running maximum: on a strictly larger gap replace the winners list, on an equal gap append the token (duplicates included).
Hint 4
Case is irrelevant for the gap computation, but the returned token must keep its original surface form.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the text on whitespace to obtain the tokens. For each token, collect the ASCII letters (ch.isascii() and ch.isalpha()) in lower-cased form. If a token has none, it is not a word and is skipped. Otherwise, its gap is abs(ord(first) - ord(last)); because every lower-cased ASCII letter shares the same 'a' offset, this difference equals the absolute difference of the a=0..z=25 positions, and abs makes the order irrelevant.
Track the best gap seen so far together with the tokens that achieve it:
- if the gap is strictly larger than the current best, replace the best and reset the token list to this token;
- if the gap equals the current best, append the token (so repeated occurrences are all listed, in input order);
- otherwise ignore the token.
If no token had a letter, return (0, []).
Why it is correct
For each token, the collected letter list contains exactly the ASCII letters in order of appearance, so its first and last elements are the token's true boundary letters; leading, trailing, and inner punctuation is ignored, and lower-casing makes the gap case-insensitive. Hence each computed gap is exactly the gap defined in the statement.
The running best is maintained by induction over the tokens: after processing any prefix of the token list, best_gap is the maximum gap in that prefix and best_words holds exactly the tokens of that prefix attaining it, in order of appearance and including repeats — a strictly larger gap clears all previous winners, an equal gap adds one more, and a smaller gap changes nothing. Therefore the final pair is the required answer. When no token contains a letter the list stays empty and (0, []) is returned.
Complexity
Let n be the length of the text. The scan is O(n) time: splitting is linear and every character is examined a constant number of times. Auxiliary space is O(k + m), where k is the length of the longest token and m is the size of the returned token list; in the worst case this is O(n). Excluding the output, extra space is O(longest token).
Reference solution
from typing import List, Tuple
def max_alpha_gap(text: str) -> Tuple[int, List[str]]:
"""Return (maximum gap, surface-form tokens achieving it)."""
best_gap = -1
best_words = []
for token in text.split():
letters = [ch.lower() for ch in token if ch.isascii() and ch.isalpha()]
if not letters:
continue
gap = abs(ord(letters[0]) - ord(letters[-1]))
if gap > best_gap:
best_gap = gap
best_words = [token]
elif gap == best_gap:
best_words.append(token)
if best_gap == -1:
return 0, []
return best_gap, best_words
max_word_letter_span = max_alpha_gap