884. Uncommon Words from Two Sentences
Explanation
- Split the input sentences
s1
ands2
into words. - Count the frequency of each word in both sentences.
- Identify the uncommon words based on the conditions given in the problem.
- Return the list of uncommon words.
Time Complexity: O(n) Space Complexity: O(n)
import java.util.*;
class Solution {
public String[] uncommonFromSentences(String s1, String s2) {
Map<String, Integer> count = new HashMap<>();
for (String word : (s1 + " " + s2).split(" ")) {
count.put(word, count.getOrDefault(word, 0) + 1);
}
List<String> uncommon = new ArrayList<>();
for (String word : count.keySet()) {
if (count.get(word) == 1) {
uncommon.add(word);
}
}
return uncommon.toArray(new String[0]);
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.