LeetCode in Kotlin

3843. First Element with Unique Frequency

Medium

You are given an integer array nums.

Return an integer denoting the first element (scanning from left to right) in nums whose frequency is unique. That is, no other integer appears the same number of times in nums. If there is no such element, return -1.

Example 1:

Input: nums = [20,10,30,30]

Output: 30

Explanation:

Example 2:

Input: nums = [20,20,10,30,30,30]

Output: 20

Explanation:

Example 3:

Input: nums = [10,10,20,20]

Output: -1

Explanation:

Constraints:

Solution

class Solution {
    fun firstUniqueFreq(nums: IntArray): Int {
        val c1: MutableMap<Int?, Int?> = HashMap<Int?, Int?>()
        for (a in nums) {
            c1[a] = c1.getOrDefault(a, 0)!! + 1
        }
        val c2: MutableMap<Int?, Int?> = HashMap<Int?, Int?>()
        for (f in c1.values) {
            c2[f] = c2.getOrDefault(f, 0)!! + 1
        }
        for (a in nums) {
            if (c2[c1[a]] == 1) {
                return a
            }
        }
        return -1
    }
}