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;
}
function longestWord(s: string): string {
let best = '';
for (const w of s.split(' ')) if (w.length > best.length) best = w;
return best;
}
def longest_word(s: str) -> str:
best = ''
for w in s.split(' '):
if len(w) > len(best):
best = w
return best
<?php
function longestWord(string $s): string
{
$best = '';
foreach (explode(' ', $s) as $w) {
if (strlen($w) > strlen($best)) {
$best = $w;
}
}
return $best;
}
class Solution {
public String longestWord(String s) {
String best = "";
for (String w : s.split(" ")) if (w.length() > best.length()) best = w;
return best;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy
- Make an Acronym · Easy