Longest Word

Easy · rating 1000 · Strings

Read a single line of words separated by single spaces. Print the longest word. If several words share the maximum length, print the one that appears first.

Editorial

Approach

Scan the words tracking the longest seen so far, starting from the first word. Because you only replace the best when a word is strictly longer, the earliest word wins any tie automatically.

words = input().split(' ')
best = words[0]
for w in words:
    if len(w) > len(best):
        best = w
print(best)

Complexity

Time: O(n). Space: O(1).

Related problems

Open Longest Word in Code Arena →