Words Buildable from Two Different Entries in a Set
StringsAuto-graded · 20 test casesLast 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:
pandqare both non-empty,pandqboth appear as entries ofwords,pandqare 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^41 <= len(words[i]) <= 100- All entries of
wordsare 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Load every string into a hash set pool so membership tests are cheap. Then, for each word word of length L, try each cut position cut from 1 to L - 1, producing a candidate pair head = word[:cut] and tail = word[cut:]. If both pieces are in pool and head != tail, the word qualifies: append it and break out of the cut loop so it is added at most once.
The head != tail check captures the "distinct entries" rule. Since the input strings are unique, an equal pair would mean reusing the same list position twice, which is forbidden. For example, with ["a", "aa"] the cut of "aa" yields "a" and "a", which is rejected, so "aa" is not reported.
Afterwards the collected words are sorted alphabetically and returned.
Why it is correct
- Every qualifying word is found. If
word = p + qwithp,qpresent in the list andp != q, then both pieces are non-empty, solen(p)is a valid cut position in[1, L-1]. At that position the loop sees both pieces inpooland differing, so it recordsword. - No unqualified word slips in. A word is recorded only when some cut yields two pieces that are in
pooland differ — exactly the definition. - No duplicates. The loop breaks after the first successful cut, and the input has no repeated entries, so each word is appended at most once.
- A word never builds itself. Each piece is strictly shorter than
word, so neither piece can equalword; there is no need to removewordfrom the set before testing it. - Exactly two pieces. Only one cut is examined per candidate, so words requiring three or more list words (like
"abc"from"a","b","c") are excluded.
Complexity
Let N be the number of words and L the maximum word length.
- Building the set:
O(N * L)time for hashing the strings. - Checking cuts: at most
L - 1cuts per word, each slicing and hashingO(L)characters →O(N * L^2). - Sorting up to
Nresults of length up toL:O(N log N * L). - Overall:
O(N * L^2 + N log N * L)time, usually summarized asO(N * L^2). - Space:
O(N * L)for the set and the output, plusO(L)for temporary slices.
Reference solution
from typing import List
def list_two_part_words(words: List[str]) -> List[str]:
pool = set(words)
answer = []
for word in words:
for cut in range(1, len(word)):
head, tail = word[:cut], word[cut:]
if head != tail and head in pool and tail in pool:
answer.append(word)
break
answer.sort()
return answer