Longest word

Longest word

Given a sentence (words separated by single spaces), return the longest word. If two words tie for longest, return the one that appears first.

longestWord(sentence)

Examples

longestWord("what a wonderful world")  // → "wonderful"
longestWord("the quick brown fox")     // → "quick"
longestWord("hi")                      // → "hi"

Walkthrough

Thinking it through

This is another "scan once, remember the best" problem — but with two twists: you're comparing words instead of numbers, and there's a tie-breaking rule hiding in the requirements.

Step one: split before you scan

A sentence is just one long string, but the question is really about individual words. Split it on whitespace first so you have a list of words to walk through. Watch for extra or repeated spaces — you want the words themselves, not empty strings left over from the split.

Step two: track the longest as you go

Once you have a list of words, this is the same shape as "find the largest number": keep a running "best word so far" and compare each new word's length against it. Update your best whenever you find something longer.

The tie-breaking trap

Here's the subtle part: when two words are equally long, the first one should win. If your comparison replaces the best whenever a new word's length is "greater than or equal to" the current best, a later tied word will quietly overwrite an earlier one — the opposite of what you want.

The fix: only replace your best when the new word is strictly longer, never on a tie. Since you're scanning left to right, the first word to reach a given length is the one that sticks, and a strict > comparison alone guarantees "first word wins."

Why this works and what to avoid

A tempting but wasteful alternative: collect every word, compute all their lengths, scan for the max, then look the word back up. That's extra passes and extra memory for no benefit. You only need one word's worth of state — the current best — so a single left-to-right scan is enough.

This is the same pattern as finding a maximum value, just applied to string length, with one wrinkle: the direction of your inequality (> vs >=) decides whether the first or last of several tied answers wins. That detail comes up anywhere a problem asks for "the first/last of several equally good answers."

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.