fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. bool checkDuplicate(vector<int>& a, int k) {
  5. unordered_map<int, int> mpp; // Stores the last index of each element
  6.  
  7. for (int i = 0; i < a.size(); i++) {
  8. if (mpp.count(a[i]) && abs(mpp[a[i]] - i) <= k) {
  9. return true;
  10. }
  11. mpp[a[i]] = i; // Update the last occurrence index
  12. }
  13. return false;
  14. }
  15.  
  16. int main() {
  17. int n;
  18. cin >> n;
  19. vector<int> arr(n);
  20.  
  21. for (int i = 0; i < n; i++) {
  22. cin >> arr[i];
  23. }
  24.  
  25. int k;
  26. cin >> k;
  27.  
  28. cout << (checkDuplicate(arr, k) ? "True" : "False");
  29. return 0;
  30. }
  31.  
Success #stdin #stdout 0.01s 5280KB
stdin
7
10 5 3 4 3 5 6
3
stdout
True