Duplicate within K Distance in an Array
Last Updated :
04 Feb, 2025
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
#include <stdio.h>
int checkDuplicatesWithinK(int arr[], int n, int k)
{
// 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 1;
}
}
return 0;
}
// Driver method to test above method
int main()
{
int arr[] = {10, 5, 3, 4, 3, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%s\n", checkDuplicatesWithinK(arr, n, 3) ? "Yes" : "No");
return 0;
}
Java
import java.util.Arrays;
class GfG {
static boolean checkDuplicatesWithinK(int[] arr, int k) {
int n = arr.length;
// 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;
}
public static void main(String[] args) {
int[] arr = {10, 5, 3, 4, 3, 5, 6};
System.out.println(checkDuplicatesWithinK(arr, 3) ? "Yes" : "No");
}
}
Python
def check_duplicates_within_k(arr, k):
n = len(arr)
# Traverse for every element
for i in range(n):
# Traverse next k elements
for c in range(1, k + 1):
j = i + c
# If we find one more occurrence within k
if j < n and arr[i] == arr[j]:
return True
return False
# Driver method to test above method
arr = [10, 5, 3, 4, 3, 5, 6]
print("Yes" if check_duplicates_within_k(arr, 3) else "No")
C#
using System;
class GfG
{
static bool CheckDuplicatesWithinK(int[] arr, int k)
{
int n = arr.Length;
// 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;
}
public static void Main()
{
int[] arr = { 10, 5, 3, 4, 3, 5, 6 };
Console.WriteLine(CheckDuplicatesWithinK(arr, 3) ? "Yes" : "No");
}
}
JavaScript
function checkDuplicatesWithinK(arr, k) {
const n = arr.length;
// Traverse for every element
for (let i = 0; i < n; i++) {
// Traverse next k elements
for (let c = 1; c <= k && (i + c) < n; c++) {
const 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
const arr = [10, 5, 3, 4, 3, 5, 6];
console.log(checkDuplicatesWithinK(arr, 3) ? "Yes" : "No");
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.
- Create an empty HashSet.
- 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
/* 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
# Python 3 program to Check if a given array
# contains duplicate elements within k distance
# from each other
def checkDuplicatesWithinK(arr, n, k):
# Creates an empty list
myset = set()
# 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.add(arr[i])
# Remove the k+1 distant item
if (i >= k):
myset.remove(arr[i - k])
return False
# Driver Code
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#
/* C# program to Check if a given
array contains duplicate elements
within 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");
}
}
JavaScript
// JavaScript program to Check if a given array contains duplicate
// elements within k distance from each other
function checkDuplicatesWithinK(arr, k) {
// Creates an empty hashset
const s = new Set();
// Traverse the input array
for (let i = 0; i < arr.length; i++) {
// If already present in hash, then we found
// a duplicate within k distance
if (s.has(arr[i]))
return true;
// Add this item to hashset
s.add(arr[i]);
// Remove the k+1 distant item
if (i >= k)
s.delete(arr[i - k]);
}
return false;
}
// Driver method to test above method
const arr = [10, 5, 3, 4, 3, 5, 6];
if (checkDuplicatesWithinK(arr, 3))
console.log('Yes');
else
console.log('No');
Time Complexity: O(n), as we are iterating through elements only once.
Auxiliary Space: O(k), to store the k elements in HashSet.
Similar Reads
Find duplicate elements in an array Given an array of n integers. The task is to find all elements that have more than one occurrences. The output should only be one occurrence of a number irrespective of the number of occurrences in the input array.Examples: Input: {2, 10, 10, 100, 2, 10, 11, 2, 11, 2}Output: {2, 10, 11}Input: {5, 40
11 min read
Check for Array Contains Duplicate III Given an integer array arr[] and two integers indexDifference and valueDifference, find a pair of indices (i, j) such that: i != jabs(i - j) <= indexDifferenceabs(arr[i] - arr[j]) <= valueDifferenceReturn true if such a pair exists, false otherwise. Example: Input: arr = [1,2,3,1], indexDiffer
6 min read
Maximise distance by rearranging all duplicates at same distance in given Array Given an array arr[] of N integers. Arrange the array in a way such that the minimum distance among all pairs of same elements is maximum among all possible arrangements. The task is to find this maximum value. Examples: Input: arr[] = {1, 1, 2, 3}Output: 3Explanation: All possible arrangements are:
6 min read
Print all Distinct (Unique) Elements in given Array Given an integer array arr[], print all distinct elements from this array. The given array may contain duplicates and the output should contain every element only once.Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}Output: {12, 10, 9, 45, 2}Input: arr[] = {1, 2, 3, 4, 5}Output: {1, 2, 3, 4,
11 min read
Sort an Array of Points by their distance from a reference Point Given an array arr[] containing N points and a reference point P, the task is to sort these points according to their distance from the given point P. Examples: Input: arr[] = {{5, 0}, {4, 0}, {3, 0}, {2, 0}, {1, 0}}, P = (0, 0) Output: (1, 0) (2, 0) (3, 0) (4, 0) (5, 0) Explanation: Distance betwee
7 min read
Find duplicates in constant array with elements 0 to N-1 in O(1) space Given a constant array of n elements which contains elements from 1 to n-1, with any of these numbers appearing any number of times. Find any one of these repeating numbers in O(n) and using only constant memory space. Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 3} Output : 3 As the given array is
12 min read
Minimum distance between any two equal elements in an Array Given an array arr, the task is to find the minimum distance between any two same elements in the array. If no such element is found, return -1. Examples: Input: arr = {1, 2, 3, 2, 1} Output: 2 Explanation: There are two matching pairs of values: 1 and 2 in this array. Minimum Distance between two 1
11 min read
Sort integers in array according to their distance from the element K Given an array arr[] of N integers and an integer K, the task is to sort these integers according to their distance from given integer K. If more than 1 element is at the same distance, print them in increasing order.Note: Distance between two elements in the array is measured as the difference betw
8 min read
Construct an Array having K Subarrays with all distinct elements Given integers N and K, the task is to construct an array arr[] of size N using numbers in the range [1, N] such that it has K sub-arrays whose all the elements are distinct. Note: If there are multiple possible answers return any of them. Examples: Input: N = 5, K = 8Output: {1, 2, 3, 3, 3}Explanat
7 min read
Duplicates in an array in O(n) and by using O(1) extra space Given an array arr[] of n elements that contains elements from 0 to n-1, with any of these numbers appearing any number of times. The task is to find the repeating numbers.Note: The repeating element should be printed only once.Example: Input: n = 7, arr[] = [1, 2, 3, 6, 3, 6, 1]Output: 1, 3, 6Expla
5 min read