Count all whitespace-separated words from both sentences in one map and keep entries with frequency one.
Complexity
O(n + m) time and O(n + m) space.
Return words that occur exactly once across two sentences combined.
Count all whitespace-separated words from both sentences in one map and keep entries with frequency one.
O(n + m) time and O(n + m) space.
package main
import "strings"
func uncommonFromSentences(s1 string, s2 string) []string {
counts := map[string]int{}
for _, word := range strings.Fields(s1 + " " + s2) {
counts[word]++
}
result := []string{}
for word, count := range counts {
if count == 1 {
result = append(result, word)
}
}
return result
}
from collections import Counter
class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> list[str]:
counts = Counter((s1 + " " + s2).split())
return [word for word, count in counts.items() if count == 1]
function uncommonFromSentences(s1: string, s2: string): string[] {
const counts = new Map<string, number>();
for (const word of (s1 + " " + s2).split(" ")) counts.set(word, (counts.get(word) ?? 0) + 1);
return [...counts].filter(([, count]) => count === 1).map(([word]) => word);
}