KatInterview

Words Buildable from Two Different Entries in a Set

StringsAuto-graded · 20 test cases
MediumAuto-gradedStringshash-setstringssorting

Last updated

Use a hash set to test every split point of each word, reporting words formable as two distinct list entries, sorted.

You are given a list words in which every entry is a distinct string of lowercase English letters. Call a word from the list splittable if it can be written as p + q (concatenation, in that order) where:

  • p and q are both non-empty,
  • p and q both appear as entries of words,
  • p and q are not the same string.

Because the entries are unique, "not the same string" is equivalent to "occupying two different positions in the list." Consequently a word cannot qualify by splitting into two identical halves — the list holds only one copy of that half, so it cannot be consumed twice.

Return every splittable word exactly once, in ascending alphabetical order, no matter how many valid split points a word has. Words that are merely a prefix or suffix of another entry (without the complementary piece also being present) do not qualify.

Constraints

  • 0 <= len(words) <= 10^4
  • 1 <= len(words[i]) <= 100
  • All entries of words are distinct.
  • Every character is a lowercase English letter.
  • Length-1 words have no split point and never qualify.
  • With fewer than two words, return an empty list.

Examples

Example 1

Input: list_two_part_words(['cat', 'dog', 'catdog', 'dogcat', 'bird'])

Output: ['catdog', 'dogcat']

Example 2

Input: list_two_part_words(['a', 'b', 'ab', 'abc'])

Output: ['ab']

Hints

Hint 1

Comparing every ordered pair of words is wasteful. Instead, walk over each possible cut position inside a word and ask whether both resulting pieces are in a set built from the whole list.

Hint 2

A single winning split is enough: once you find one, record the word and stop scanning its remaining cut positions so it is appended only once.

Hint 3

The two pieces must be different strings. If they come out equal, only one copy of that string exists in the list, so the split is invalid.