fork download
  1. #include <bits/stdc++.h>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5.  
  6. bool fnc(vector<int> arr,int k){
  7. unordered_map<int,int> mp;
  8. for(int i=0;i<arr.size();i++){
  9. if(mp.find(arr[i]) != mp.end() && i-mp[arr[i]]<=k){
  10. return true;
  11. }
  12.  
  13. mp[arr[i]]=i;
  14. }
  15.  
  16. return false;
  17.  
  18.  
  19.  
  20. }
  21.  
  22. int main(){
  23. vector<int> arr={1, 2, 2, 1, 2, 3};
  24. int k=2;
  25. if (fnc(arr, k)) {
  26. cout << "There are two equal numbers within distance " << k << std::endl;
  27. } else {
  28. cout << "No two equal numbers found within distance " << k << std::endl;
  29. }
  30. return 0;
  31.  
  32. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
There are two equal numbers within distance 2