Given a list of strings strings, group them so that two strings are considered identical if they contain the same words regardless of word order and case. For example, "Hello World" and "world hello" are identical.
Return a list containing only the last occurrence of each group, while preserving the relative order based on the first appearance of each group in the input.
Function Signature
def normalize_strings(strings: list[str]) -> list[str]:
...
Rules
-
Words are compared case-insensitively. Two strings belong to the same group when their lowercased words are the same multiset: the same words, each appearing the same number of times, in any order. So
"go go stop"
and
"stop go"
are different groups.
-
Each output element is the original string of the group's last occurrence, unchanged (same case, same word order).
-
Groups appear in the output in the order of their first occurrence in the input.
Constraints
-
1 <= len(strings) <= 10^4
-
1 <= len(strings[i]) <= 200
-
Each string consists of words separated by single spaces.
-
Words contain only English letters (uppercase or lowercase).
Examples
Input: strings = ["Hello World", "world hello", "Foo Bar", "bar foo", "HELLO WORLD"]
Output: ["HELLO WORLD", "bar foo"]
"Hello World", "world hello" and "HELLO WORLD" form one group, and "HELLO WORLD" is its last occurrence. "Foo Bar" and "bar foo" form another, with "bar foo" last. The hello group comes first because it appears first in the input, even though its last occurrence is at the end.
Input: strings = ["apple banana", "Banana Apple", "cherry", "CHERRY", "Apple BANANA"]
Output: ["Apple BANANA", "CHERRY"]
"apple banana", "Banana Apple" and "Apple BANANA" are one group (last: "Apple BANANA"). "cherry" and "CHERRY" are another (last: "CHERRY").
Input: strings = ["go go stop", "Stop Go", "GO stop go"]
Output: ["GO stop go", "Stop Go"]
"go go stop" and "GO stop go" both contain "go" twice and "stop" once, so they form one group whose last occurrence is "GO stop go". "Stop Go" has "go" only once, so it is a group of its own.