oneby7

Tries Prefix trees

424. Longest Word in Dictionary

Medium

You are given a list of lowercase words, words. Return the longest word in the list that can be built one letter at a time, where each step along the way is also a word in the list.

So a word can be built when all its shorter prefixes are in words: its first letter on its own, its first two letters, and so on. For example, "cab" can be built if the list also holds "c" and "ca". A one-letter word can always be built.

If several words of the greatest length can be built, return the one that comes first in alphabetical order. If no word can be built, return the empty string. Answers are shown in double quotes, so an empty answer shows as "".

Example 1

Input: words = ["c", "ca", "cab", "cabs", "cart", "carts"]

Output: "cabs"

Explanation: "c", "ca" and "cab" are all in the list, so "cabs" can be built. "carts" is longer, but "car" is not in the list, so neither "cart" nor "carts" can be built.

Example 2

Input: words = ["y", "ye", "yes", "o", "on", "one", "yet"]

Output: "one"

Explanation: "yes", "yet" and "one" can all be built, and each has three letters. "one" comes first in alphabetical order.

Example 3

Input: words = ["it", "its", "ice"]

Output: ""

Explanation: No word in the list has one letter, so no word can start a chain. "its" would need "i" as well as "it".

Check your understanding

Work out the answer for this input before you write any code.

words = ["d", "do", "dog", "dot", "cob", "cobs", "b", "bo", "bog"]

Constraints

  • 1 ≤ words.length ≤ 105
  • 1 ≤ words[i].length ≤ 30
  • All the words together hold at most 106 letters.
  • words[i] holds only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.