Contains-DuplicateII

This is a variation of the previous problem. Again, this is best solved using hashmap.

class Solution {
    fun containsNearbyDuplicate(nums: IntArray, k: Int): Boolean {
        val map = HashMap<Int, Int>()
        
        nums.forEachIndexed { index, value ->
            if(map.containsKey(value)){
                if(index - map[value]!! <= k) return true else map[value] = index
            }else map[value] = index
        }
        
        return false
        
    }
}
Runtime: 248 ms, faster than 62.96% of Kotlin online submissions for Contains Duplicate II.
Memory Usage: 45.8 MB, less than 100.00% of Kotlin online submissions for Contains Duplicate II.
comments powered by Disqus