progress

~/problems / Arrays & hashing / Python toolkit

The k longest words with nlargest

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~10 min

Write longest_words(words: list[str], k: int) -> list[str] that returns the k longest words of words, using heapq.nlargest.

  • The longest word comes first.
  • Words of the same length keep the order they have in words.
  • A word that appears several times counts each time. If k is at least len(words), return every word in that order; k == 0 gives [].
longest_words(["fig", "banana", "kiwi", "cherry", "plum", "apple"], 3)
# ["banana", "cherry", "apple"]

longest_words(["ab", "cd", "e"], 5)
# ["ab", "cd", "e"]
  • 0 <= len(words) <= 10^5, 0 <= k <= 10^5, and words are 1 to 30 lower-case letters.
  • Don't modify words.
Show hint

heapq.nlargest(k, iterable, key=...) takes the same key argument as sorted, and its result is the same as sorted(iterable, key=..., reverse=True)[:k], ties included.

Topic: Python toolkit. Counter, deque, heapq, bisect, itertools: the standard library to know cold, and its traps.

0:00
Ctrl ' run · Ctrl ↵ submit
esc