Optimal Java Solution for Extracting Rare Words in Sentences
IntuitionThe task is to find words that are uncommon between two sentences. An "uncommon word" is one that appears exactly once across both sentences. To solve
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The task is to find words that are uncommon between two sentences. An "uncommon word" is one that appears exactly once across both sentences. To solve this, the first thought is to count the occurrences of each word and then filter out the words that occur only once.

# Approach
<!-- Describe your approach to solving the problem. -->
- Concatenate the Sentences: Combine both sentences (s1 and s2) into a single string with a space in between to treat all words as part of one sentence.

- Split Words and Count Frequencies: Use split(" ") to break the concatenated string into individual words. Use a HashMap to count the frequency of each word.

- Filter Uncommon Words: Iterate through the HashMap and select words that appear exactly once (frequency = 1).

- Convert Result to Array: Add the selected words to a List and convert it to an array using toArray(new String[0]).

# Complexity
- Time complexity: O(n+m)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Splitting the string: O(n), where n is the total number of characters in s1 + s2. Iterating through words to count frequencies: O(m), where m is the number of words. Filtering and adding uncommon words: O(m).
Overall:O(n+m).
- Space complexity: O(k+u)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
- Storing words and their counts in a HashMap: O(k), where k is the number of unique words. Storing the result in a List: O(u), where u is the number of uncommon words.
Overall: O(k+u).

# Code
```java []
class Solution {
    public String[] uncommonFromSentences(String s1, String s2) {
        HashMap<String, Integer> wordCount = new HashMap<>();
        for (String word : (s1 + " " + s2).split(" ")) {
            wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
        }
        List<String> result = new ArrayList<>();
        for (String word : wordCount.keySet()) {
            if (wordCount.get(word) == 1) {
                result.add(word);
            }
        }
        return result.toArray(new String[0]);
    }
}
```
['Java']