Open In App

Duplicate within K Distance in an Array

Last Updated : 04 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given an integer array arr[] and an integer k, determine whether there exist two indices i and j such that arr[i] == arr[j] and |i – j| ≤ k. If such a pair exists, return ‘Yes’, otherwise return ‘No’.

Examples: 

Input: k = 3, arr[] = [1, 2, 3, 4, 1, 2, 3, 4]
Output: No
Explanation: Each element in the given array arr[] appears twice and the distance between every element and its duplicate is 4.

Input: k = 3, arr[] = [1, 2, 3, 1, 4, 5]
Output: Yes
Explanation: 1 is present at index 0 and 3.

Input: k = 3, arr[] = [1, 2, 3, 4, 5]
Output: No
Explanation: There is no duplicate element in arr[].

[Naive Approach] – O(n * k) Time and O(1) Space

The idea is to run two loops. The outer loop picks every index i as a starting index, and the inner loop compares all elements which are within k distance of i, i.e. i + k.

Below is given the implementation:

C++
#include <bits/stdc++.h>
using namespace std;

bool checkDuplicatesWithinK(vector<int> &arr, int k)
{
    int n = arr.size();
  
    // Traverse for every element
    for (int i = 0; i < n; i++) {
      
        // Traverse next k elements 
        for (int c = 1; c <= k && (i + c) < n; c++) {
            int j = i + c;
          
            // If we find one more occurrence 
            // within k
            if (arr[i] == arr[j])
              return true;
        }
    }
    return false;
}

// Driver method to test above method
int main()
{
    vector<int> arr = {10, 5, 3, 4, 3, 5, 6};
    if (checkDuplicatesWithinK(arr, 3))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}
C Java Python C# JavaScript

Output
Yes

Time Complexity: O(n * k), for each element of the array arr[], we are iterating up to next k elements.
Auxiliary Space: O(1)

[Expected Approach] – Using HashSet – O(n) Time and O(k) Space

The idea is to use HashSet to store elements of the array arr[] and check if there is any duplicate present within a k distance. Also remove elements that are present at more than k distance from the current element. Following is a detailed algorithm.

  1. Create an empty HashSet. 
  2. Traverse all elements from left to right. Let the current element be ‘arr[i]’ 
    • If the current element ‘arr[i]’ is present in a HashSet, then return true. 
    • Else add arr[i] to hash and remove arr[i-k] from hash if i >= k

Below is given the implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// C++ program to Check if a given array contains duplicate
// elements within k distance from each other
bool checkDuplicatesWithinK(vector<int> &arr, int k) {
    // Creates an empty hashset
    unordered_set<int> s;

    // Traverse the input array
    for (int i = 0; i < arr.size(); i++) {
      
        // If already present in hash, then we found
        // a duplicate within k distance
        if (s.find(arr[i]) != s.end())
            return true;

        // Add this item to hashset
        s.insert(arr[i]);

        // Remove the k+1 distant item
        if (i >= k)
            s.erase(arr[i - k]);
    }
    return false;
}

// Driver method to test above method
int main () {
    vector<int> arr = {10, 5, 3, 4, 3, 5, 6};
    if (checkDuplicatesWithinK(arr, 3))
        cout << "Yes";
    else
        cout << "No";
}
Java Python C# JavaScript

Output
Yes

Time Complexity: O(n), as we are iterating through elements only once.
Auxiliary Space: O(k), to store the k elements in HashSet.



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg