Skip to content
ExamSpine

Lesson 5.10 · Write it

The longest word

A functionPython or Java9 tests, 5 of them hidden

On a phone? Put the lines in order instead

Write a function that returns the longest word in a sentence.

  1. The words are separated by exactly one space, with no space at the start or the end. There is always at least one word, and words contain only letters.
  2. If two or more words are equally long, return the first of them.
  3. Return the word exactly as it is in the sentence.
  4. Write the search yourself. The shortcuts listed with this question are not allowed.

Only the text your function returns is checked, exactly.

def longest_word(sentence: str) -> str

You cannot use these in this question:

  • max()
  • min()
  • sorted()
  • .sort()
  • import heapq

Practise splitting and the longest-so-far loop by writing them yourself. The shortcuts listed are not allowed.

Examples

Your function is tested on 9 cases: the 4 examples below, and 5 hidden ones that check the rules above.

  • longest_word("a big elephant") should return "elephant": the longest word is the last word
  • longest_word("the quick brown fox") should return "quick": quick and brown are equally long, so the first wins (rule 2)
  • longest_word("I like it") should return "like": a later word shorter than the longest so far, but longer than the first word
  • longest_word("sun") should return "sun": one word

public static String longestWord(String sentence)

Checking whether Java answers can run here.

You cannot use these in this question:

  • Arrays.sort()
  • Arrays.parallelSort()
  • Collections.max()
  • Collections.min()
  • .sort()
  • .stream()
  • .max()
  • .min()
  • import java.util.stream

Practise splitting and the longest-so-far loop by writing them yourself. The shortcuts listed are not allowed.

Examples

Your function is tested on 9 cases: the 4 examples below, and 5 hidden ones that check the rules above.

  • longestWord("a big elephant") should return "elephant": the longest word is the last word
  • longestWord("the quick brown fox") should return "quick": quick and brown are equally long, so the first wins (rule 2)
  • longestWord("I like it") should return "like": a later word shorter than the longest so far, but longer than the first word
  • longestWord("sun") should return "sun": one word
solution.pySolution.java