Uncommon Words From Two Sentences

I really don’t like my solution for this one but it’s enough for now. Maybe one way to optimize this is not to use the map and filter operators and just use pure for-loops.

class Solution {    
    val uniqueWords:(List<String>)->List<String> = {
        it.groupBy {it}.filter {it.value.size == 1}.map {it.key}
    }
    
    fun uncommonFromSentences(A: String, B: String): Array<String> {
        val aWords = A.split(" ")
        val bWords = B.split(" ")
        
        return (uniqueWords(aWords).filter { !(it in bWords)} + uniqueWords(bWords).filter { !(it in aWords)}).toTypedArray()
    }
}
Runtime: 184 ms, faster than 47.37% of Kotlin online submissions for Uncommon Words from Two Sentences.
Memory Usage: 36.2 MB, less than 100.00% of Kotlin online submissions for Uncommon Words from Two Sentences.

We’ll use the groupBy operator to put each word into a map and their corresponding occurence in the sentence. Then we’ll use filter to select only those words which has single occurence.

Once we got the list of single-occurence words, we’ll do another filter to remove those words that exists in B sentence. We will do this on both A and B sentences. Finally, we’ll combine the results for A and B and return an array of Strings.