Contains Duplicate ll

Moderate
0/80
Average time to solve is 35m
30 upvotes
Asked in companies
CiscoAmazonWipro

Problem statement

Given an array 'arr' of 'N' integers and an integer 'K'. The array 'arr' may contain duplicate integers. Return "true" if the array contains any duplicate element within the 'K' distance from each other, otherwise, return "false".

Detailed explanation ( Input/output format, Notes, Images )
Input format :
The first line of input contains a single integer T, representing the number of test cases or queries to be run.

Then the T test cases follow:

The first line of each test case contains two single space-separated integers 'N', and 'K', denoting the size of the array 'arr'  and the distance respectively. 

The second line of each test case contains 'N' single space-separated integers, elements of the array.  
Output format :
For each test case, print “true” if the array contains any duplicate element within the 'K' distance from each other, otherwise, print "false".

Result for each test case will be printed in a separate line.
Note
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
1 <= N <= 10^5
1 <= K <= 10^5
-10^9 <= arr[i] <= 10^9

Time Limit: 1sec
Sample Input 1 :
1
5 2
3 4 9 4 2 
Sample Output 1 :
true
Explanation For Sample Output 1 :
From index 1 to 3 there are two 4’s.
Sample Input 2 :
1
10 4
3 2 0 -4 7 -9 -8 10 5 -1
Sample Output 2 :
false
Explanation For Sample Output 2 :
There is no duplicate element within a distance of 4 in the given array .
Hint

Check for all possible subarray of size ‘K’.

Approaches (3)
Brute Force

The naive approach is to run two loops, the outer loop will pick each element one by one.

The inner loop compares all elements which are within ‘K’ distance from and with the currently selected element. 

If the selected element matches with any of the elements that we are comparing in the inner loop then it means there is a duplicate.

Time Complexity

O(K*N) per test case, where N is the size of the array and K is distance.

 

In the worst case, for each element in the array (O(N)), we will be checking the subarray of K elements (O(K)). Thus a total of O(N * K) time.   

Space Complexity

O(1)

 

 Constant extra space is used.

Code Solution
(100% EXP penalty)
Contains Duplicate ll
Full screen
Console