fork download
  1. #include <iostream>
  2. #include <unordered_map>
  3. using namespace std;
  4.  
  5. #define fo(i,start,end) for(int i=start;i<end;i++)
  6.  
  7. int main() {
  8. int arr[] = {3, 2, 4, 3, 1};
  9. int k = 3; // distance
  10. int n = 5; // size
  11.  
  12. // Store every element and its last occurrence index
  13. unordered_map<int, int> mp;
  14.  
  15. fo(i, 0, n){
  16. // 1. Check if the element already exists in the map
  17. if(mp.find(arr[i]) != mp.end()) {
  18.  
  19. // 2. Calculate distance using the PREVIOUS occurrence
  20. int distance = i - mp[arr[i]];
  21.  
  22. // 3. If it's within distance k, we found our match
  23. if(distance <= k) {
  24. cout << "True" << endl;
  25. return 0;
  26. }
  27. }
  28.  
  29. // 4. Update the map with the CURRENT index
  30. // We do this whether it was found or not, because we always want
  31. // to keep the most recent index for future comparisons.
  32. mp[arr[i]] = i;
  33. }
  34.  
  35. cout << "False" << endl;
  36. return 0;
  37. }
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
True