1.

Write a function to determine whether duplicate elements in a given array are within a given distance of each other.

Answer»


  • Input: arr[] = {1, 2, 3, 4, 2, 1, 2} range=3


  • Output: True

class Solution {
public:

bool checkDuplicatesWithinRange(vector<int> arr, int range)
{
// Creating an empty hashset
unordered_set<int> myset;

// Traversing the input array
for (int i = 0; i < arr.size(); i++)
{
// If already present in hashset, then we found a duplicate within range distance
if (myset.find(arr[i]) != myset.end())
return true;

// Add this item to hashset
myset.insert(arr[i]);

// Remove the range+1 distant item from the hashset
if (i >= range)
myset.erase(arr[i-range]);
}
return false;
}
};


  • Time Complexity: O(n)


  • Space Complexity: O(n)




Discussion

No Comment Found