Contains-Duplicate

There are multiple ways to solve this problem. One could sort the arrays and check element by element if two consecutive items are equal.

Another approach is to use a list to store elements that has been processed and if indexOf(element) is not -1 then return true. I tried this but it’s slow.

My final solution uses hashmap to keep track of processed elements. This is definitely way faster particulary when the array size is huge.

class Solution {
    fun containsDuplicate(nums: IntArray): Boolean {
        val map = HashSet<Int>()
        nums.forEach {
            if(map.contains(it)) return true            
            map.add(it)
        }
        
        return false
    }
}
Runtime: 228 ms, faster than 83.15% of Kotlin online submissions for Contains Duplicate.
Memory Usage: 38 MB, less than 100.00% of Kotlin online submissions for Contains Duplicate.
comments powered by Disqus