0

in Python, if you use set() and in operator, you can see whether an exists in a set in O(1). However, in javascript, is it possible to do the same with the same time complexity? I have usually done

var arr = [1,2,3,4,5];
if (arr.indexOf(3) != -1) return true; // element exists!

without being really sure about its efficiency.

Maximus S
  • 10,759
  • 19
  • 75
  • 154
  • 2
    Well indexOf() is the proper way to check for an element in an array. As for the efficiency I suppose you'd need to run some tests. – j08691 Nov 07 '14 at 17:41
  • You can change `if (arr.indexOf(3) != -1) return true;` to `return arr.indexOf(3) != -1;` because the statements returns true. – ntzm Nov 07 '14 at 17:43
  • Why do you need the answer so quickly? You can set up an O(1) operation by putting everything in an object. – amphetamachine Nov 07 '14 at 17:43
  • Not directly. It depends on how its implemented in the engine. You could transform your array into a map, which would give you `O(1)` lookup time, but then you'd lose array semantics. – Vivin Paliath Nov 07 '14 at 17:45
  • I am quite surprised by this. Then, if you had an array whose size is 1Billion and you have to check whether "x" exists in the array. What is the most conventional way of doing that in javascript? Is not having a hashtable a drawback of javascript? – Maximus S Nov 07 '14 at 19:01

0 Answers0