Easy 0 solved 0% acceptance

Longest Word

Find the longest word in a sentence.

What you'll learn

  • Split a sentence into words
  • Track the longest word seen so far
  • Break ties by keeping the first one

Problem

Return the longest word in text (words are separated by spaces). If several words share the longest length, return the first one.

Implement longest_word(text).

Input

text: The sentence.

Output

Return the longest word, or an empty string if there are no words.

Constraints

0 ≤ length ≤ 10,000

Examples

Example 1
Input:
text = "I love programming"

Expected output:
expected = "programming"
Input:
std::string text = "I love programming";

Expected output:
std::string expected = "programming";
Input:
string text = "I love programming";

Expected output:
string expected = "programming";

Explanation

"programming" has 11 letters, more than the others.

Example 2
Input:
text = "cat dog cow"

Expected output:
expected = "cat"
Input:
std::string text = "cat dog cow";

Expected output:
std::string expected = "cat";
Input:
string text = "cat dog cow";

Expected output:
string expected = "cat";

Explanation

All are 3 letters; the first, "cat", wins.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Compare words by length while scanning the text once.

Hint 2

Keep the first word seen with the maximum length so ties stay in order.

Hint 3

Handle the case where the text has no words at all.

Expected complexity

O(n) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.