fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. bool checkDuplicatesWithinK(int arr[], int n, int k)
  6. {
  7. // Creates an empty unordered map
  8. unordered_map<int,int> umap;
  9.  
  10.  
  11. for(int i=0; i<n; i++)// start traversing the array from left to right
  12. {
  13. if (umap.find(arr[i]) == umap.end())// if the element is not present in map then insert it
  14. {
  15. umap[arr[i]] = i;
  16. }
  17.  
  18. else // if it is already present then check the condition
  19. {
  20. if(i-umap[arr[i]] <= k)
  21. {return true;// if duplicate present within a distance k
  22. }
  23. umap[arr[i]] = i;
  24. }
  25. }
  26.  
  27.  
  28. return false;// if the duplicate is not present
  29. }
  30.  
  31. int main() {
  32. int arr[] = {10, 5, 3, 4, 3, 5, 6};
  33. int n = sizeof(arr) / sizeof(arr[0]);
  34. if (checkDuplicatesWithinK(arr, n, 3))
  35. cout << "Yes";
  36. else
  37. cout << "No";
  38. }
Success #stdin #stdout 0s 5432KB
stdin
Standard input is empty
stdout
Yes