Check if a given array contains duplicate elements within k distance from each other

27 Jun, 2022
Given an unsorted array that may contain duplicates. Also given a number k which is smaller than size of array. Write a function that returns true if array contains duplicates within k distance.Examples: 
Input: k = 3, arr[] = {1, 2, 3, 4, 1, 2, 3, 4}
Output: false
All duplicates are more than k distance away.

Input: k = 3, arr[] = {1, 2, 3, 1, 4, 5}
Output: true
1 is repeated at distance 3.

Input: k = 3, arr[] = {1, 2, 3, 4, 5}
Output: false

Input: k = 3, arr[] = {1, 2, 3, 4, 4}
Output: true
A Simple Solution is to run two loops. The outer loop picks every element ‘arr[i]’ as a starting element, the inner loop compares all elements which are within k distance of ‘arr[i]’. The time complexity of this solution is O(kn). 
Implementation:
C++
Java
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(int arr[], int n, int k){     // traversing the input array    for (int i = 0; i < n; i++) {        int j = i + 1;        int range = k;        // searching in next k-1 elements if its duplicate        // is present or not        while (range > 0 and j < n) {            if (arr[i] == arr[j])                return true;            j++;            range--;        }    }    return false;} // Driver method to test above methodint main(){    int arr[] = { 10, 5, 3, 4, 3, 5, 6 };    int n = sizeof(arr) / sizeof(arr[0]);    if (checkDuplicatesWithinK(arr, n, 3))        cout << "Yes";    else        cout << "No";} // This article is contributed by Arpit Jain
public class GFG{     /* Java program to Check if a given array contains    duplicate elements within k distance from each other */  public static boolean    checkDuplicatesWithinK(int[] arr, int n, int k)  {     // traversing the input array    for (int i = 0; i < n; i++) {      int j = i + 1;      int range = k;      // searching in next k-1 elements if its      // duplicate is present or not      while (range > 0 && j < n) {        if (arr[i] == arr[j]) {          return true;        }        j++;        range--;      }    }    return false;  }   // Driver method to test above method  public static void main(String[] args)  {    int[] arr = { 10, 5, 3, 4, 3, 5, 6 };    int n = arr.length;    if (checkDuplicatesWithinK(arr, n, 3)) {      System.out.print("Yes");    }    else {      System.out.print("No");    }  }} // This article is contributed by Aarti_Rathi
/* C# program to Check if a givenarray contains duplicate elementswithin k distance from each other */using System;using System.Collections.Generic; class GFG {    static bool checkDuplicatesWithinK(int[] arr, int n,                                       int k)    {        // traversing the input array        for (int i = 0; i < n; i++) {            int j = i + 1;            int range = k;            // searching in next k-1 elements if its            // duplicate is present or not            while (range > 0 && j < n) {                if (arr[i] == arr[j])                    return true;                j++;                range--;            }        }        return false;    }     // Driver code    public static void Main(String[] args)    {        int[] arr = { 10, 5, 3, 4, 3, 5, 6 };        int n = arr.Length;        if (checkDuplicatesWithinK(arr, n, 3))            Console.WriteLine("Yes");        else            Console.WriteLine("No");    }} // This code has been contributed by Aarti_Rathi
Yes
We can solve this problem in Θ(n) time using Hashing. The idea is to one by add elements to hash. We also remove elements which are at more than k distance from current element. Following is detailed algorithm.
Create an empty hashtable. Traverse all elements from left from right. Let the current element be ‘arr[i]’ If current element ‘arr[i]’ is present in hashtable, then return true. Else add arr[i] to hash and remove arr[i-k] from hash if i is greater than or equal to k
Create an empty hashtable. 
Traverse all elements from left from right. Let the current element be ‘arr[i]’ If current element ‘arr[i]’ is present in hashtable, then return true. Else add arr[i] to hash and remove arr[i-k] from hash if i is greater than or equal to k
If current element ‘arr[i]’ is present in hashtable, then return true. 
Else add arr[i] to hash and remove arr[i-k] from hash if i is greater than or equal to k
Implementation:
C++
Java
Python 3
C#
Javascript
#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(int arr[], int n, int k){    // Creates an empty hashset    unordered_set<int> myset;     // Traverse the input array    for (int i = 0; i < n; i++)    {        // If already present n hash, then we found        // a duplicate within k distance        if (myset.find(arr[i]) != myset.end())            return true;         // Add this item to hashset        myset.insert(arr[i]);         // Remove the k+1 distant item        if (i >= k)            myset.erase(arr[i-k]);    }    return false;} // Driver method to test above methodint main (){    int arr[] = {10, 5, 3, 4, 3, 5, 6};    int n = sizeof(arr) / sizeof(arr[0]);    if (checkDuplicatesWithinK(arr, n, 3))        cout << "Yes";    else        cout << "No";} //This article is contributed by Chhavi
/* Java program to Check if a given array contains duplicate   elements within k distance from each other */import java.util.*; class Main{    static boolean checkDuplicatesWithinK(int arr[], int k)    {        // Creates an empty hashset        HashSet<Integer> set = new HashSet<>();         // Traverse the input array        for (int i=0; i<arr.length; i++)        {            // If already present n hash, then we found            // a duplicate within k distance            if (set.contains(arr[i]))               return true;             // Add this item to hashset            set.add(arr[i]);             // Remove the k+1 distant item            if (i >= k)              set.remove(arr[i-k]);        }        return false;    }     // Driver method to test above method    public static void main (String[] args)    {        int arr[] = {10, 5, 3, 4, 3, 5, 6};        if (checkDuplicatesWithinK(arr, 3))           System.out.println("Yes");        else           System.out.println("No");    }}
# Python 3 program to Check if a given array# contains duplicate elements within k distance# from each otherdef checkDuplicatesWithinK(arr, n, k):     # Creates an empty list    myset = []     # Traverse the input array    for i in range(n):             # If already present n hash, then we        # found a duplicate within k distance        if arr[i] in myset:            return True         # Add this item to hashset        myset.append(arr[i])         # Remove the k+1 distant item        if (i >= k):            myset.remove(arr[i - k])    return False # Driver Codeif __name__ == "__main__":         arr = [10, 5, 3, 4, 3, 5, 6]    n = len(arr)    if (checkDuplicatesWithinK(arr, n, 3)):        print("Yes")    else:        print("No") # This code is contributed by ita_c
/* C# program to Check if a givenarray contains duplicate elementswithin k distance from each other */using System;using System.Collections.Generic; class GFG{    static bool checkDuplicatesWithinK(int []arr, int k)    {        // Creates an empty hashset        HashSet<int> set = new HashSet<int>();         // Traverse the input array        for (int i = 0; i < arr.Length; i++)        {            // If already present n hash, then we found            // a duplicate within k distance            if (set.Contains(arr[i]))                return true;             // Add this item to hashset            set.Add(arr[i]);             // Remove the k+1 distant item            if (i >= k)                set.Remove(arr[i - k]);        }        return false;    }     // Driver code    public static void Main (String[] args)    {        int []arr = {10, 5, 3, 4, 3, 5, 6};        if (checkDuplicatesWithinK(arr, 3))            Console.WriteLine("Yes");        else            Console.WriteLine("No");    }} // This code has been contributed// by 29AjayKumar
<script> /* Javascript program to Check if a given array contains duplicate   elements within k distance from each other */             function checkDuplicatesWithinK(arr, n, k)    {        // Creates an empty hashset        let myset = [];                 // Traverse the input array        for(let i=0;i<n;i++)        {            // If already present n hash, then we found            // a duplicate within k distance            if(arr.includes(arr[i]))            {                return true;            }            // Add this item to hashset            myset.add(arr[i]);                         // Remove the k+1 distant item            if (i >= k)            {                index = array.indexOf(arr[i - k]);                array.splice(index, 1);            }        }        return false;    }    // Driver method to test above method    let arr = [10, 5, 3, 4, 3, 5, 6];    let n= arr.length;    if (checkDuplicatesWithinK(arr, n, 3))    {        document.write("Yes");    }    else    {        document.write("No");    }              // This code is contributed by rag2127     </script>
Yes
Check if a given array contains duplicate elements within k distance from each other | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersCheck if a given array contains duplicate elements within k distance from each other | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:51•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=hzRo7dLtQHs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Anuj. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ukasp
29AjayKumar
rag2127
111arpit1
codewithrathi
hardikkoriintern
codewithmini
Amazon
Arrays
Hash
Amazon
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.