AlgoInsight

DSA problem

Find the Longest Word in a Sentence

EasyStringsPattern: String TraversalbeginnerFree

Given a sentence s, find and return the longest word. If multiple words share the maximum length, return the first one.

Split the sentence by spaces and iterate through the words, tracking the longest word and its length, updating whenever you find a longer one. This is a find-maximum problem applied to strings instead of numbers; the same pattern finds the shortest word, the word with the most vowels, or the most frequent word. Edge cases include leading/trailing spaces, multiple spaces between words, and punctuation attached to words. In real applications this kind of text analysis powers search engines, readability scoring, and content optimization.

Examples

Example 1
Input: s = "I love programming with AlgoInsight"
Output: "programming"
Explanation: Both "programming" and "AlgoInsight" have 11 characters; since the first longest word wins on a tie, "programming" is returned.
Example 2
Input: s = "the quick brown fox"
Output: "quick"
Explanation: "quick" and "brown" both have 5 characters; the earlier word, "quick", is returned.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

string

Browse all DSA problems