FastPrepLongest Word Containing Another Input

Longest Word Containing Another Input

Meta logoMeta● HardFULLTIMEPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

Given an array of nonempty lowercase English strings words, find an input string that contains at least one other input string as a contiguous substring.

An input at index i qualifies when some index j != i satisfies that words[j] occurs in words[i]. Equal strings at different indices count as a match; a string does not match itself at the same index.

Return the longest qualifying string. If several qualifying strings have the same length, return the one appearing first in the input array. Return the empty string "" when none qualifies. Matching is literal and case-sensitive.

Optimization discussion

A direct baseline checks every ordered pair and compares characters at every possible substring start. Explain its time and space cost, then describe two faster approaches and implement one. Length-based pruning and multi-pattern search are useful directions.

Only the returned string is graded; the complexity discussion is interview practice.

Function

findContainingWord(words: String[]) → String

Examples

Example 1

words = ["programming","am","pro"]return = "programming"

programming contains both am and pro. It is the longest qualifying input.

Example 2

words = ["category","cat"]return = "category"

cat is a prefix substring of category. The containing word is returned.

Example 3

words = ["dog","cat","bird"]return = ""

No input contains another listed input, so return the empty string.

Constraints

  • 1 <= words.length <= 200.
  • 1 <= words[i].length <= 2000.
  • The total length of all input strings is at most 20000.
  • Every string contains only letters a through z; duplicate strings are allowed.

More Meta problems

See Meta hiring insights
public String findContainingWord(String[] words) {
    // Write your code here.
}
words["programming","am","pro"]
expected"programming"
Checking account…