AlgoMaster Logo

Contains Duplicate II

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The simplest approach to solve this problem is to check every pair of elements in the array. If two elements are the same and are within the given range k from each other, we return true. Otherwise, we continue checking all possible pairs.

Code:

2. Sliding Window with HashSet

Intuition:

Instead of checking each pair, we can use a sliding window of size k and a HashSet to track the elements within that window. As we slide the window through the array, we can keep checking if the current element already exists in the HashSet. If it does, it means we found a duplicate within the given range.

Code:

3. Sliding Window with HashMap

Intuition:

A small optimization can be done over the HashSet approach by using a HashMap which stores the indices. By keeping track of indices, we can avoid unnecessary otherwise possible duplicates removal. This approach reduces operations to a bare minimum required for ensuring unique elements within the window.

Code: