Find the Largest Word in a String
Problem
Given a sentence s containing words separated by spaces, return the longest word. If several words tie for the longest length, return the one that appears first.
Input / Output
- Input: string
s. - Output: the longest word (empty string if
shas no words).
Examples
Example 1
Input: s = "the quick brown fox jumped"
Output: "jumped"
Example 2
Input: s = "a bb cc dd"
Output: "bb" (first of the length-2 words)
Example 3
Input: s = " "
Output: ""
Constraints
0 <= s.length <= 10^5
Approach
Scan the string once, tracking the start of the current word. When a space (or the end of the string) is reached, compare the finished word's length to the best so far and update only if it is strictly longer — that guarantees the first of equal-length words wins.
Handling punctuation is a common extension: strip non-letters before measuring, or treat any non-letter as a separator.
max(s.split(), key=len) is the one-liner; it also returns the first maximal element because max keeps the first maximum it sees, but you should be able to explain the manual scan.
Complexity
- Time: O(n)
- Space: O(1) extra (besides the returned word).
Reference solution (Python)
def largest_word(s: str) -> str:
best_start = best_len = 0
i, n = 0, len(s)
while i < n:
if s[i] == ' ':
i += 1
continue
j = i
while j < n and s[j] != ' ':
j += 1
if j - i > best_len:
best_start, best_len = i, j - i
i = j
return s[best_start:best_start + best_len]
Test cases
| Input | Expected |
|---|---|
"the quick brown fox jumped" | "jumped" |
"a bb cc dd" | "bb" |
" " | "" |
"single" | "single" |