Coding problem · Easy · Basics

Longest Word in a Sentence

Easy Algorithms & data structures

Given a sentence s of words separated by single spaces, return the longest word. If several words share the maximum length, return the first of them.

Example 1

Input: s = "I love programming puzzles"
Output: "programming"

Example 2

Input: s = "cat dog"
Output: "cat"
Explanation: Both have 3 letters; cat comes first.

Hints

Hint 1

Keep track of the best word so far while you loop.

Hint 2

Only replace it when a word is strictly longer, so ties keep the earlier word.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(n)

One pass over the words: if the current word is longer than the best so far, it becomes the best. Using > (not >=) keeps the first of equally long words.

Reference solution

function longestWord(s) {
  let best = '';
  for (const w of s.split(' ')) if (w.length > best.length) best = w;
  return best;
}

Was this page helpful?