
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Check if a given array contains duplicate elements within k distance from each in C++
Here we will see how to check whether an unsorted array has duplicate elements within k distance from each other or not. Suppose a list of elements is {1, 2, 3, 1, 4, 5}, here if k = 3, then the program will return true, as the distance between two 1s is 3.
We will solve this using a hash table. The steps will be like below −
- Create one empty hash table
- For each index i, let the element e = arr[i] in the list, do
- if e is present in the hash table, then return true
- otherwise, add e to hash table, and remove (i-k)th element from the hash table if it exists, when i >= K.
Example
#include<iostream> #include<set> using namespace std; bool hasDuplicateWithDistK(int arr[], int n, int k) { set<int> element_set; for (int i = 0; i < n; i++) { if (element_set.find(arr[i]) != element_set.end()) return true; element_set.insert(arr[i]); if (i >= k) element_set.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 (hasDuplicateWithDistK(arr, n, 3)) cout << "Duplicate element has found"; else cout << "Duplicate element has not found"; }
Output
Duplicate element has found
- Related Articles
- Check if an array contains all elements of a given range in Python
- How to check if array contains a duplicate number using C#?
- Write a program in Python to check if a series contains duplicate elements or not
- Java Program to Check if An Array Contains a Given Value
- Golang Program to Check if An Array Contains a Given Value
- How to redundantly remove duplicate elements within an array – JavaScript?
- Python – Insert character in each duplicate string after every K elements
- Java Program to Check if An Array Contains the Given Value
- How to check if a data frame column contains duplicate values in R?
- C# program to find if an array contains duplicate
- Removing duplicate elements from an array in PHP
- Write a Golang program to find duplicate elements in a given array
- Check if an array contains the elements that match the specified conditions in C#
- Check if list contains all unique elements in Python
- How to print array elements within a given range using Numpy?

Advertisements