KatInterview

Longest Word That Swallows Another Word in the List

StringsAuto-graded · 25 test cases
MediumAuto-gradedStringsstringssubstringsorting

Last updated

Find the longest distinct word in a list that contains a different word from the list as a contiguous substring, with a fixed tie-break and empty-string handling.

You are given a list of strings words. Find a word that has some other word from the same list inside it as a contiguous substring.

Rules

  • Compare values, not positions. Duplicate entries collapse into one word, so a word never counts as containing "another" word just because it appears twice. For example, ["ab", "ab"] has no qualifying word.
  • A word qualifies if some different word (a different string value) in the list occurs inside it as a contiguous substring.
  • The empty string "" is a substring of every string. If "" is in the list, every non-empty word qualifies because of it.
  • If several words qualify, return the longest one. If several qualifying words share that longest length, return the lexicographically largest of them (standard Python string comparison).
  • If no word qualifies, return the empty string "".

Example of the rules

With ["programming", "am", "pro"], the word "programming" contains both "am" and "pro". It is the only qualifying word, so it is returned.

Constraints

  • 0 <= len(words) <= 2000
  • Each word may be empty, and each has length at most 200.
  • Words may contain any characters.
  • The list may contain duplicates.
  • Return "" when the list is empty or no word qualifies.

Examples

Example 1

Input: find_enclosing_word(['programming', 'am', 'pro'])

Output: 'programming'

Hints

Hint 1

If two distinct strings are such that one contains the other, which of the two must be longer? What does that say about which pairs you actually need to test?

Hint 2

Remove duplicates first, then order the words by length. A word can only contain words that are strictly shorter, so consider containers from longest to shortest.

Hint 3

To get the required tie-break, make sure that among words of equal length you try the lexicographically larger one first. Then the first container you find that holds some shorter word is the answer.