Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Problem Statement
2.
Naive approach
2.1.
Algorithm
2.2.
Code in C++
2.3.
Code in Java
2.4.
Code in Python
3.
Efficient Approach
3.1.
Algorithm
3.2.
Code in C++
3.3.
Code in Java
3.4.
Code in Python
4.
Frequently Asked Question
4.1.
What is an array?
4.2.
What is Hashing?
4.3.
What is an unordered set?
4.4.
Whаt аre the three bаsic operаtions on а hаsh tаble?
4.5.
How to find an element in a set?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

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

Author Alok Pandey
0 upvote

Problem Statement

You are given an unsorted array that may contain duplicates. A number k that is less than the size of the array is also provided. Write a function that takes an array, an integer k, and the size of an array n, as input and the function returns true if the array contains duplicates within k distance.

Must Recommended Topic, Hash Function in Data Structure.

Examples: 

Input: 

k = 2, arr[] = {2, 2, 1, 4, 1, 2}

Output: 

true

 

2 is repeated at distance 2.

Input: 

k = 3, arr[] = {9, 2, 1, 8, 4, 5}

Output: 

false

 

Input: 

k = 4, arr[] = {6, 2, 8, 6, 5}

Output: 

true

 

6 is repeated at distance 4.

Naive approach

The first and easiest solution is Running two loops. The inner loop checks all items that are within k distance of "arr[i]" after the outer loop chooses every element "arr[i]" as a starting element. This solution has a time complexity (kn). 

Algorithm

  • Create a function that takes arr[], k, and n as parameters.
  • Run the first loop to traverse the whole array.
  • Inside this loop, start another loop to search next k-1 elements
  • if their duplicates are present, return True
  • Else False

 

Let's take an example to better understand the algorithm.

k = 2, arr[] = {9,5,5,4}

Step 1: Take Array as input 

Step 2: Take the first element of the array = 9 and initialize a variable w=k

Step 3: Match with the next element and if the element is not equal reduce the value of w

 

Step 4: if the value of w<0, come out of the loop and take another element of the array and perform step 3 and step 4.

Step 5: The element 5 matches with the next element and returns Yes.

Code in C++

Implementation in C++ to check if a given array contains duplicate elements within k distance from each other.

#include <bits/stdc++.h>
using namespace std;
bool checkDuplicates(int arr[], int n, int k)
{
	for (int i = 0; i < n; i++) {
		int window = k;
		for(int j=i+1;window>0 && j<n;j++){
			if (arr[i] == arr[j])
				return true;
			window--; 
		}
	}
	return false;
}

int main()
{
	int arr[] = { 14, 4, 7, 4, 9, 4, 6 };
	int n = sizeof(arr) / sizeof(arr[0]);
	if (checkDuplicates(arr, n, 3))
		cout << "Yes";
	else
		cout << "No";
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

Yes

Code in Java

Implementation in Java to check if a given array contains duplicate elements within k distance from each other.

public class Main
{
	public static boolean checkDuplicates(int[] arr, int n, int k)
	{
		for (int i = 0; i < n; i++)
		{
			int window = k;
			for (int j = i + 1;window > 0 && j < n;j++)
			{
				if (arr[i] == arr[j])
				{
					return true;
				}
				window--;
			}
		}
		return false;
	}
	
	public static void main(String[] args)
	{
		int[] arr = {14, 4, 7, 4, 9, 4, 6};
		int n = arr.length;
		if (checkDuplicates(arr, n, 3))
		{
			System.out.print("Yes");
		}
		else
		{
			System.out.print("No");
		}
	}
}
You can also try this code with Online Java Compiler
Run Code

 

Output

Yes

Code in Python

Implementation in Python to check if a given array contains duplicate elements within k distance from each other.

def main():
    arr = [14, 4, 7, 4, 9, 4, 6]
    n = len(arr)
    if Globals.checkDuplicates(arr, n, 3):
        print("Yes", end = '')
    else:
        print("No", end = '')


class Globals:
    @staticmethod
    def checkDuplicates(arr, n, k):
        for i in range(0, n):
            window = k
            j = i+1
            while window>0 and j<n:
                if arr[i] == arr[j]:
                    return True
                window -= 1
                j += 1
        return False
if __name__ == "__main__":
    main()
You can also try this code with Online Python Compiler
Run Code

 

Output

Yes

 

Time complexity: 0(kn)

There are nested loops present in the solution and the time complexity will depend on the condition of the loop. The first loop is running n time and the second one depends on the parameter k hence time complexity will be 0(kn).

Space Complexity-O(1)

We haven't stored the value anywhere in the code hence space complexity will be O(1)

Efficient Approach

Using hashing, we can resolve this issue in (n) time. To add elements to hash one by one is the idea. Additionally, we exclude components that are farther away from the present element than k.  

Algorithm

  • Create a function that takes arr[], k, and n as parameters.
  • Creates an empty unordered_set HashSet
  • Run a loop to traverse the whole array.
  • Inside loop check either any element in the array is repeated then insert that element in the hash set.
  • Remove the k+1 distant item.

    Let's take an example to better understand the algorithm
    k = 2, arr[] = {9,6,5,4,5,2}

 

Step 1: Take Array as input 

Step 2: Copy the first element of the array in an unordered set

Step 3: Copy the next element until i<k. i=1,k=2 and check for similar element.

Step 4: Copy the next element until i<k. i=2,k=2

Step 5: Delete the [i-k-1]th element because i>k. i=3,k=2 

Step 6: Insert the next element and check for similar element.

We had found that number 5 had occurred twice. hence we will return Yes.

Code in C++

Implementation in C++ to check if a given array contains duplicate elements within k distance from each other.

#include<bits/stdc++.h>
using namespace std;
 bool checkDuplicates(int nums[], int n,int k)
    {
       unordered_set<int> s;
       
       if (k <= 0) return false;
       if (k >= n) k = n - 1;
       
       for (int i = 0; i < n; i++)
       {
           if (i > k) s.erase(nums[i - k - 1]);
           if (s.find(nums[i]) != s.end()) return true;
           s.insert(nums[i]);
       }
       
       return false;
    }
    int main ()
{
    int arr[] = {1,0,1,1};
    int n = sizeof(arr) / sizeof(arr[0]);
    if (checkDuplicates(arr, n, 1))
        cout << "Yes";
    else
        cout << "No";
}
You can also try this code with Online C++ Compiler
Run Code

 

OUTPUT

Yes

Code in Java

Implementation in Java to check if a given array contains duplicate elements within k distance from each other.

import java.util.*;
public class Main
{
	 public static boolean checkDuplicates(int[] nums, int n, int k)
	 {
		   HashSet<Integer> s = new HashSet<Integer>();

		   if (k <= 0)
		   {
			   return false;
		   }
		   if (k >= n)
		   {
			   k = n - 1;
		   }

		   for (int i = 0; i < n; i++)
		   {
			   if (i > k)
			   {
				   s.remove(nums[i - k - 1]);
			   }
			   if (s.contains(nums[i]))
			   {
				   return true;
			   }
			   s.add(nums[i]);
		   }

		   return false;
	 }
	public static void main(String[] args)
	{
		int[] arr = {1, 0, 1, 1};
		int n = arr.length;
		if (checkDuplicates(arr, n, 1))
		{
			System.out.print("Yes");
		}
		else
		{
			System.out.print("No");
		}
	}
}
You can also try this code with Online Java Compiler
Run Code

 

OUTPUT

Yes

Code in Python

Implementation in Python to check if a given array contains duplicate elements within k distance from each other.

def main():
    arr = [1, 0, 1, 1]
    n = len(arr)
    if Globals.checkDuplicates(arr, n, 1):
        print("Yes", end = '')
    else:
        print("No", end = '')

class Globals:
    @staticmethod
    def checkDuplicates(nums, n, k):
        s = []
        if k <= 0:
            return False
        if k >= n:
            k = n - 1
        for i in range(0, n):
            if i > k:
                s.remove(nums[i - k - 1])
            if nums[i] in s:
                return True
            s.append(nums[i])
        return False
        
if __name__ == "__main__":
    main()
You can also try this code with Online Python Compiler
Run Code

 

OUTPUT

Yes

 

Time Complexity-O(n)
There is only one loop present in the solution and running n times so the time complexity is O(n).

Space Complexity-O(n)
We have used the set to store the value hence the space complexity will be O(n).


You can also read about the Longest Consecutive Sequence.

Frequently Asked Question

What is an array?

An array is a collection of homogeneous values stored at contiguous memory locations. It is like a staircase, in which each value of placed at every step, and elements can be accessed by knowing the stair number (or index number).

What is Hashing?

Hashing is a technique using which a given value can be transformed into another value. It makes searching more accessible and quicker.

What is an unordered set?

An unordered set is a data structure that is a associative container that holds a collection of singular Key objects. Average constant-time complexity characterizes search, insertion, and removal. Internally, the components are arranged into buckets rather than being sorted in any specific sequence.

Whаt аre the three bаsic operаtions on а hаsh tаble?

There are mainly three basic operations of a hash table.

  • Insert − inserts аn element in а hаsh tаble. 
  • Seаrch − Seаrches аn element in а hаsh tаble. 
  • Delete − Deletes аn element from а hаsh tаble.

How to find an element in a set?

A built-in method in the C++ STL called set::find returns an iterator to the element that was looked for in the set container. If the element cannot be located, the iterator then moves to the spot immediately following the final element in the set.

Conclusion

In this article, we have extensively discussed the problem of Check if a given array contains duplicate elements within k distance from each other.

We hope that this blog has helped you enhance your knowledge of the array data structure and set traversal  and if you would like to learn more, check out our articles on


Check out the following problems - 

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. 

Enroll in our courses and refer to the mock test and problems available.

Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow. 

Happy Coding!

Live masterclass