Middle+
Implement a function to filter duplicates in linear time O(n) without using Set, by using an object as a hash table.
sobes.tech AI
Answer from AI
Here is an example of a JavaScript function that filters duplicates from an array in linear time O(n), using an object as a hash table, without using Set:
function filterDuplicates(arr) {
const seen = {};
const result = [];
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
if (!seen[item]) {
seen[item] = true;
result.push(item);
}
}
return result;
}
// Example usage:
const data = [1, 2, 3, 2, 4, 1, 5];
console.log(filterDuplicates(data)); // [1, 2, 3, 4, 5]
Here, the seen object stores already encountered elements as keys, which allows for quick checking of an element's presence and adding only unique values to the final array.