Longest Word Finder - Problem

Given a sentence as a string, find and return the longest word in the sentence.

If there are multiple words with the same maximum length, return the first occurrence.

Note: Words are separated by spaces, and you can assume the input contains only alphabetic characters and spaces.

Input & Output

Example 1 — Basic Case
$ Input: sentence = "The quick brown fox jumps"
Output: "brown"
💡 Note: Words are ["The"(3), "quick"(5), "brown"(5), "fox"(3), "jumps"(5)]. Maximum length is 5. First word with length 5 is "brown".
Example 2 — Single Word
$ Input: sentence = "Hello"
Output: "Hello"
💡 Note: Only one word exists, so "Hello" is the longest word.
Example 3 — All Equal Length
$ Input: sentence = "cat dog pig"
Output: "cat"
💡 Note: All words have length 3. Return first occurrence "cat".

Constraints

  • 1 ≤ sentence.length ≤ 104
  • sentence contains only lowercase and uppercase English letters and spaces
  • sentence does not start or end with a space

Visualization

Tap to expand
INPUTALGORITHM STEPSFINAL RESULT"The quick brown fox jumps"Sentence with 5 wordsNeed to find longest word1Scan Each CharacterProcess sentence left to right2Build Current WordCollect characters until space3Compare LengthsUpdate longest if current > max4Return First MaxReturn first word with max lengthWord lengths:The: 3, quick: 5, brown: 5fox: 3, jumps: 5Maximum length: 5First occurrence: brownbrownKey Insight:Track the longest word in a single pass - no need to store all words in memory!TutorialsPoint - Longest Word Finder | Single Pass Algorithm
Asked in
Google 25 Microsoft 18 Amazon 22
28.5K Views
Medium Frequency
~8 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen