# Max Length Token

> The longest token wins.

Canonical URL: <https://datadriven.io/problems/max_length_token>

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.

## 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

**Whitespace tokenization with length tracking**

```python
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 best
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the string length. Splitting is O(n) and the scan is O(w) where w is the word count.
> 
> **Space:** O(n) for the split result.

> **Interviewers Watch For**
>
> Using strict `>` instead of `>=` for the comparison. This ensures the first word wins ties, matching the requirement.

> **Common Pitfall**
>
> Using `>=` which returns the last word of maximum length instead of the first.

---

## Common 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.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/max_length_token)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.