LeetCode in Kotlin

2085. Count Common Words With One Occurrence

Easy

Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays.

Example 1:

Input: words1 = [“leetcode”,”is”,”amazing”,”as”,”is”], words2 = [“amazing”,”leetcode”,”is”]

Output: 2

Explanation:

Thus, there are 2 strings that appear exactly once in each of the two arrays.

Example 2:

Input: words1 = [“b”,”bb”,”bbb”], words2 = [“a”,”aa”,”aaa”]

Output: 0

Explanation: There are no strings that appear in each of the two arrays.

Example 3:

Input: words1 = [“a”,”ab”], words2 = [“a”,”a”,”a”,”ab”]

Output: 1

Explanation: The only string that appears exactly once in each of the two arrays is “ab”.

Constraints:

Solution

class Solution {
    fun countWords(words1: Array<String>, words2: Array<String>): Int {
        var count = 0
        val map = HashMap<String, Int>()
        val map1 = HashMap<String, Int>()
        // Putting the "words1" array in the map
        for (s in words1) {
            if (!map.containsKey(s)) {
                map[s] = 1
            } else {
                map[s] = map[s]!! + 1
            }
        }
        // Putting "words2" array in another map
        for (s in words2) {
            if (!map1.containsKey(s)) {
                map1[s] = 1
            } else {
                map1[s] = map1[s]!! + 1
            }
        }
        // traversing through the "words1" array
        for (s in words1) {
            // Checking if the key is present and is matching in both maps
            // and if the key has appeared just one time in "map1" map
            if (map[s] == map1[s] && map1[s] == 1) {
                count++
            }
        }
        return count
    }
}