Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the Set.has() method O(1) and Array.indexOf O(n)? [duplicate]

I have seen in an answer that the Set.has() method is O(1) and Array.indexOf() is O(n).

var a = [1, 2, 3, 4, 5];
a.indexOf(5);          


s = new Set(a);
s.has(5);              //Is this O(1)?

Is Set.has() really O(1) ?

like image 292
Charlie Avatar asked Mar 08 '19 05:03

Charlie


People also ask

What is the function of the indexOf () in arrays?

indexOf() The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Can you use indexOf for an array?

Introduction to the JavaScript array indexOf() method To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

Is Set Has faster than array includes?

Adding elements to a collection push array method is about 4 times faster than the . add set method, no matter the number of elements being added.

Do sets have indexes JS?

By contrast, Sets are a keyed collection. Instead of using indices, Sets order their data using keys. A Set's elements are iterable in the order of insertion, and it cannot contain any duplicate data.


1 Answers

I don't think the array that has 5 elements is good case to check time complexity.

So based on @Shidersz's snippet, I made a new one that has many elements and invoked once.

Is Set.has() really O(1) ?

Yes. Time complexity of Set.has() is O(1) according to result of the test below.

const MAX = 10000000
let a = []
a.length = MAX

for (let i = 0; i < MAX; i++) {
  a[i] = i
}

let s = new Set(a)

let o = a.reduce((acc, e) => {
  acc[e] = e
  return acc
}, {})

console.time("Test_Array.IndexOf(0)\t")
a.indexOf(0);
console.timeEnd("Test_Array.IndexOf(0)\t")
console.time("Test_Array.IndexOf(n/2)\t")
a.indexOf(MAX / 2);
console.timeEnd("Test_Array.IndexOf(n/2)\t")
console.time("Test_Array.IndexOf(n)\t")
a.indexOf(MAX);
console.timeEnd("Test_Array.IndexOf(n)\t")

console.time("Test_Set.Has(0)\t\t")
s.has(0)
console.timeEnd("Test_Set.Has(0)\t\t")
console.time("Test_Set.Has(n/2)\t")
s.has(MAX / 2)
console.timeEnd("Test_Set.Has(n/2)\t")
console.time("Test_Set.Has(n)\t\t")
s.has(MAX)
console.timeEnd("Test_Set.Has(n)\t\t")

console.time("Test_Object[0]\t\t")
o[0]
console.timeEnd("Test_Object[0]\t\t")
console.time("Test_Object[n/2]\t")
o[MAX / 2]
console.timeEnd("Test_Object[n/2]\t")
console.time("Test_Object[n]\t\t")
o[MAX]
console.timeEnd("Test_Object[n]\t\t")
.as-console {
  background-color: black !important;
  color: lime;
}

.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}
like image 62
zmag Avatar answered Sep 28 '22 03:09

zmag