Max Length Token
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L3
Problem
Given a string, split on whitespace and return the longest token. If multiple tokens tie for longest, return the first one.
The longest token wins.
Example 1
Input:
s = "the quick brown fox"
Output:
"quick"
Example 2
Input:
s = "hello"
Output:
"hello"
Worked solution and explanation
Why this problem exists in real interviews
Finding the longest word tests string splitting and tracking a running maximum with a tiebreaking rule. It is a basic string processing task that checks attention to detail on ties.
Break down the requirements
Step 1: Split the string by whitespace
Use str.split() to tokenize. This handles multiple spaces correctly.
Step 2: Track the longest word, preferring the first on ties
Use > (strict greater than) when comparing lengths so that earlier words win ties.
The solution
def longest_word(s):
words = s.split()
best = words[0]
for i in range(1, len(words)):
if len(words[i]) > len(best):
best = words[i]
return bestCommon follow-up questions
- What if the string contains punctuation attached to words? (Tests stripping punctuation before measuring length.)
- How would you return the top-k longest words? (Tests sorting by length descending and taking a slice.)
- What if the input is empty? (Tests guarding against `words[0]` on an empty split result.)