1. Introduction
The Any Duplicate Within K Distance problem is a common array and HashSet problem.
Given an integer array arr[] and an integer k, we need to check whether there are two different indices i and j such that:
arr[i] == arr[j]|i - j| <= k
In simple words, we need to find whether any element appears more than once within a distance of k indices.
We can solve this problem efficiently using a HashSet and Sliding Window technique.
2. Example
Input:
arr = [1, 5, 4, 5, 1]
k = 3Output:
trueExplanation:
The element 5 occurs at two different indices:
- First occurrence: Index 1
- Second occurrence: Index 3
Distance:
|3 - 1| = 2Since 2 <= 3, a duplicate exists within the given distance.
Therefore, the answer is true.
3. Understanding the Concepts
What is a HashSet?
A HashSet is a collection that stores only unique elements.
For example:
HashSet<int> set = new HashSet<int>();
set.Add(10);
set.Add(20);
set.Add(10);The HashSet contains:
[10, 20]The duplicate value 10 is not stored twice.
Important HashSet operations:
| Method | Purpose |
|---|---|
| Add() | Adds an element |
| Contains() | Checks whether an element exists |
| Remove() | Removes an element |
These operations take O(1) average time.
What is the Sliding Window technique?
Sliding Window is a technique where we maintain a limited range of elements while traversing an array.
In this problem, we only need to remember the previous k elements.
When we move to the next index:
- Check whether the current element already exists.
- If it exists, return
true. - Otherwise, add it to the HashSet.
- Remove the element that is outside the allowed window.
This ensures that we only check elements within the required distance.
4. C# Implementation
class Solution
{
public bool checkWithinK(int[] arr, int k)
{
HashSet<int> set = new HashSet<int>();
for (int i = 0; i < arr.Length; i++)
{
// Check whether the current element already exists
if (set.Contains(arr[i]))
{
return true;
}
// Add the current element
set.Add(arr[i]);
// Maintain the previous k elements
if (set.Count > k)
{
set.Remove(arr[i - k]);
}
}
return false;
}
}5. Step-by-Step Code Explanation
Step 1: Create a HashSet
HashSet<int> set = new HashSet<int>();We create a HashSet to store the elements from the previous indices.
Step 2: Traverse the array
for (int i = 0; i < arr.Length; i++)We iterate through every element in the array.
Step 3: Check for duplicates
if (set.Contains(arr[i]))
{
return true;
}
Join the conversation! Your thoughts help the community grow.