Given an unsorted array that may contain duplicates. Also given a number k which is smaller than the size of the array. Write a function that returns true if the 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, and the inner loop compares all elements which are within k distance of ‘arr[i]’. The time complexity of this solution is O(k * n).
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool checkDuplicatesWithinK( int arr[], int n, int k)
{
for ( int i = 0; i < n; i++) {
int j = i + 1;
int range = k;
while (range > 0 and j < n) {
if (arr[i] == arr[j])
return true ;
j++;
range--;
}
}
return false ;
}
int 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" ;
}
|
C
#include <stdbool.h>
#include <stdio.h>
bool checkDuplicatesWithinK( int arr[], int n, int k)
{
for ( int i = 0; i < n; i++) {
int j = i + 1;
int range = k;
while (range > 0 && j < n) {
if (arr[i] == arr[j])
return true ;
j++;
range--;
}
}
return false ;
}
int main()
{
int arr[] = { 10, 5, 3, 4, 3, 5, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
if (checkDuplicatesWithinK(arr, n, 3))
printf ( "Yes" );
else
printf ( "No" );
}
|
Java
public class GFG
{
public static boolean
checkDuplicatesWithinK( int [] arr, int n, int k)
{
for ( int i = 0 ; i < n; i++) {
int j = i + 1 ;
int range = k;
while (range > 0 && j < n) {
if (arr[i] == arr[j]) {
return true ;
}
j++;
range--;
}
}
return false ;
}
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" );
}
}
}
|
Python3
def checkDuplicatesWithinK(arr, n, k):
for i in range (n):
j = i + 1
range_ = k
while (range_ > 0 and j < n):
if (arr[i] = = arr[j]):
return True
j + = 1
range_ - = 1
return False
arr = [ 10 , 5 , 3 , 4 , 3 , 5 , 6 ]
n = len (arr)
if (checkDuplicatesWithinK(arr, n, 3 ) = = True ):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG {
static bool checkDuplicatesWithinK( int [] arr, int n,
int k)
{
for ( int i = 0; i < n; i++) {
int j = i + 1;
int range = k;
while (range > 0 && j < n) {
if (arr[i] == arr[j])
return true ;
j++;
range--;
}
}
return false ;
}
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" );
}
}
|
Javascript
class GFG
{
static checkDuplicatesWithinK(arr, n, k)
{
for ( var i=0; i < n; i++)
{
var j = i + 1;
var range = k;
while (range > 0 && j < n)
{
if (arr[i] == arr[j])
{
return true ;
}
j++;
range--;
}
}
return false ;
}
static main(args)
{
var arr = [10, 5, 3, 4, 3, 5, 6];
var n = arr.length;
if (GFG.checkDuplicatesWithinK(arr, n, 3))
{
console.log( "Yes" );
}
else
{
console.log( "No" );
}
}
}
GFG.main([]);
|
Time Complexity: O(N*K).
Auxiliary Space: O(1).
Another Solution using hashing:-
We can solve this problem in Θ(n) time using Hashing. The idea is to add elements to the hash. We also remove elements that are at more than k distance from the current element. Following is a detailed algorithm.
- Create an empty hashtable.
- Traverse all elements from left to right. Let the current element be ‘arr[i]’
- If the current element ‘arr[i]’ is present in a 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++
#include<bits/stdc++.h>
using namespace std;
bool checkDuplicatesWithinK( int arr[], int n, int k)
{
unordered_set< int > myset;
for ( int i = 0; i < n; i++)
{
if (myset.find(arr[i]) != myset.end())
return true ;
myset.insert(arr[i]);
if (i >= k)
myset.erase(arr[i-k]);
}
return false ;
}
int 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" ;
}
|
Java
import java.util.*;
class Main
{
static boolean checkDuplicatesWithinK( int arr[], int k)
{
HashSet<Integer> set = new HashSet<>();
for ( int i= 0 ; i<arr.length; i++)
{
if (set.contains(arr[i]))
return true ;
set.add(arr[i]);
if (i >= k)
set.remove(arr[i-k]);
}
return false ;
}
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
def checkDuplicatesWithinK(arr, n, k):
myset = []
for i in range (n):
if arr[i] in myset:
return True
myset.append(arr[i])
if (i > = k):
myset.remove(arr[i - k])
return False
if __name__ = = "__main__" :
arr = [ 10 , 5 , 3 , 4 , 3 , 5 , 6 ]
n = len (arr)
if (checkDuplicatesWithinK(arr, n, 3 )):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static bool checkDuplicatesWithinK( int []arr, int k)
{
HashSet< int > set = new HashSet< int >();
for ( int i = 0; i < arr.Length; i++)
{
if ( set .Contains(arr[i]))
return true ;
set .Add(arr[i]);
if (i >= k)
set .Remove(arr[i - k]);
}
return false ;
}
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" );
}
}
|
Javascript
<script>
function checkDuplicatesWithinK(arr, n, k)
{
let myset = [];
for (let i=0;i<n;i++)
{
if (arr.includes(arr[i]))
{
return true ;
}
myset.add(arr[i]);
if (i >= k)
{
index = array.indexOf(arr[i - k]);
array.splice(index, 1);
}
}
return false ;
}
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" );
}
</script>
|
Time Complexity: O(N).
Auxiliary Space: O(N) for using an unordered set.
This article is contributed by Anuj. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.