intermediate

Find Longest Word

Find the longest word in a sentence.

Finding the longest element in a collection is a fundamental algorithmic pattern. This exercise demonstrates how to iterate through a list, compare values, and track the optimal resultβ€”skills applicable to many real-world problems.

πŸ“š Concepts & Theory

Finding the longest word in a string is a practical problem that combines string splitting, iteration, and comparison logic. This exercise helps you understand how to process collections of items and track the "best" candidate.

Problem Breakdown:

  • Split the sentence into individual words

  • Iterate through each word

  • Track which word has the maximum length

  • Return the longest word
Approach 1: Using max() with key parameter
Python's max() function can find the maximum based on a custom criterion:
sentence = "The quick brown fox jumps"
longest = max(sentence.split(), key=len)
# Returns: "quick" or "brown" or "jumps" (all length 5)

Approach 2: Manual Iteration (Educational)
Track the longest word while iterating:

words = sentence.split()
longest_word = ""
for word in words:
if len(word) > len(longest_word):
longest_word = word

Approach 3: Using sorted()
Sort words by length and take the last one:

longest = sorted(sentence.split(), key=len)[-1]

Edge Cases to Consider:

  • Multiple words with same maximum length

  • Empty strings

  • Strings with only spaces

  • Single word sentences
The manual approach is most educational as it shows the comparison logic clearly. The max() approach is most Pythonic.

🎯 Your Challenge

Write longest_word that returns the longest word.

πŸ“ Starter Code

Python
def longest_word(sentence):
    pass

print(longest_word('The quick brown fox'))
  • Split the sentence into words first
  • Keep track of the longest word found so far
  • Compare the length of each word with your current longest
  • Update your longest word when you find a longer one
  • Start with an empty string as your initial longest word

Solution

Python
def longest_word(sentence):
    words = sentence.split()
    longest = ''
    for word in words:
        if len(word) > len(longest):
            longest = word
    return longest

print(longest_word('The quick brown fox'))

Explanation

This solution iterates through each word in the sentence, comparing its length with the current longest word found. The condition len(word) > len(longest_word) ensures we update our result only when we find a longer word. Starting with longest_word = "" ensures any word will be longer initially. If multiple words have the same maximum length, this returns the first one encountered. Time complexity: O(n) where n is the total number of characters. Space complexity: O(m) where m is the number of words.

⚠️ Common Mistakes to Avoid

  • Using >= instead of > (returns last word of max length, not first)
  • Forgetting to handle empty strings
  • Not initializing longest_word properly
  • Comparing words instead of their lengths
  • Not splitting the string before processing

❓ Frequently Asked Questions

The manual iteration approach returns the first one. Using max() might return any of them depending on implementation.
For basic version, punctuation is included in the word. Advanced versions would strip punctuation first.
Returning an empty string or raising an exception are both valid approaches. Document your choice.
max(sentence.split(), key=len) is the most Pythonic one-liner solution.

πŸ”— Related Exercises