oneby7

Tries Prefix trees

428. Longest Word With All Prefixes

Medium

You are given a list of lowercase words, words. Return the longest word in the list whose every prefix is also in the list.

A prefix of a word is its first few letters, from one letter up to the whole word: "c", "ca" and "cat" are the prefixes of "cat". So "cat" counts only if "c" and "ca" are both words in the list too.

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

Example 1

Input: words = ["top", "t", "toes", "tap", "to", "tops", "toe", "topsoil"]

Output: "toes"

Explanation: "toes" and "tops" both count, since "t", "to", "toe" and "top" are all in the list. They have the same length, and "toes" comes first in alphabetical order. "tap" needs "ta", and "topsoil" needs "topso".

Example 2

Input: words = ["ab", "abc", "abcd"]

Output: ""

Explanation: Every word starts with "a", but "a" itself is not in the list. So no word counts.

Example 3

Input: words = ["pine", "p", "pines", "pin"]

Output: "p"

Explanation: Three of the words start with "pi", but "pi" is not a word in the list. So "pin", "pine" and "pines" do not count, and only "p" does.

Check your understanding

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

words = ["send", "s", "seats", "sen", "se", "seal", "sea", "set", "sets"]

Constraints

  • 1 ≤ words.length ≤ 105
  • 1 ≤ words[i].length, and all the words together hold at most 105 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.