Last Updated: June 7, 2026
The sentence is a string of words separated by spaces, and the answer is the word with the most characters, the word itself rather than its length or position.
If two words share the maximum length, return the one that appears earlier. Extra spaces need care, so a stray double space between words does not produce an empty word as the answer.
The problem combines two operations: separate the sentence into words, then compare those words by length. The tie rule falls out naturally if you only replace the current best when a word is strictly longer.
1 <= s.length <= 1000 → The sentence has at least one word, so there is always an answer to return.Turn the sentence into a list of words first. The problem then becomes a single-pass search for the longest item, the same maximum scan you would run over a list of numbers. Track the best word so far, and replace it only when the current word is strictly longer. Using "strictly longer" rather than "longer or equal" makes the first of several equal-length words win.
Take "the quick brown fox". The first word the has length 3, so it becomes the best. The next word quick has length 5, which is strictly longer, so it takes over as the best. The word brown also has length 5, but 5 is not strictly greater than 5, so the best stays quick. The last word fox has length 3, so nothing changes. The final answer is quick.
Splitting builds a whole collection of words just to discard most of them. Avoid that extra storage by scanning the sentence character by character.
Remember where the current word started and how long it has grown. When you reach a space or the end of the sentence, the word is finished, so compare its length against the best so far. If it is strictly longer, record its start position and length. This keeps the same first-wins tie behavior using only a few index variables.
Take "a bb ccc". The scan finishes the word a at the first space, recording it as the best with length 1. It then finishes bb, which has length 2 and is strictly longer, so bb becomes the new best. The scan continues into ccc, growing the current length to 3. Reaching the end of the string closes that word, and since 3 beats the previous best of 2, ccc becomes the answer. No separate list of words is ever built. The word is finalized each time the scan crosses a space or reaches the end.