DEV Community

Debesh P.
Debesh P.

Posted on

219. Contains Duplicate II | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/contains-duplicate-ii/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/contains-duplicate-ii/solutions/7500664/most-optimal-solution-all-languages-beat-nq7m


leetcode 219


Solution

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {

        Map<Integer, Integer> map = new HashMap<>();

        int idx = 0;

        for(int i : nums) {
            if(map.containsKey(i) && Math.abs(idx - map.get(i)) <= k) {
                return true;
            }
            map.put(i, idx);
            idx++;
        }

        return false;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)