Given an array of strings words, remove every string that is a prefix of any other string in the list, while keeping the original relative order of the remaining strings.
A string s is removed if there exists a string t in words such that t != s and t starts with s (that is, s is a proper prefix of t). Identical copies of a string do not count as prefixes of each other, so duplicates are kept unless a longer string extends them.
Return the array of remaining strings.
Function Signature
def remove_prefix_strings(words: list[str]) -> list[str]:
Rules
-
The kept strings appear in the same relative order as in
words
.
-
Copies of the same string share one fate: every copy is kept, or every copy is removed because a longer string starts with it.
Constraints
-
1 <= len(words) <= 10^4
-
1 <= len(words[i]) <= 100
-
words[i]
consists of lowercase English letters.
Examples
Input: words = ["apple", "app", "banana", "ban", "band", "cat"]
Output: ["apple", "banana", "band", "cat"]
"app" is a prefix of "apple", and "ban" is a prefix of "banana" and "band", so both are removed. The rest keep their original order.
Input: words = ["a", "ab", "abc", "b"]
Output: ["abc", "b"]
"a" and "ab" are prefixes of "abc". "abc" and "b" are not prefixes of any other string.
Input: words = ["go", "go", "gone", "dog", "dog"]
Output: ["gone", "dog", "dog"]
Both copies of "go" are removed because "gone" starts with "go". The two copies of "dog" do not remove each other, and no longer string extends "dog", so both stay.