1

Consider this snippet:

const obj1 = {1:1, 2:1, 3:1}
const obj2 = {1:1, 4:1, 9:1}

for(let key in obj1){
    if(!(key ** 2 in obj2)) return false
  }

Can the Big O of this algorithm considered O(n) or it should be O(n^2) because of:

if(!(key ** 2 in obj2))

Is considered to loop through all items (search) of obj2

** Note**: assume the length of obj1 and obj2 are equal

S. Hesam
  • 1,784
  • 1
  • 11
  • 33
Tarreq
  • 1,019
  • 6
  • 14
  • 2
    It depends on an actual implementation of the property lookup algorithm. It's a good be that it's better than linear on any modern JavaScript runtime. – Pointy May 21 '20 at 20:09
  • 1
    Why would the big O of `in` operator change when it's in a for loop? – Barmar May 21 '20 at 20:11
  • 1
    @Pointy Am I the only one who thought that his concern was that `key ** 2` caused it to be quadratic? – Barmar May 21 '20 at 20:15
  • @Barmar It has nothing to do with key ** 2, my concern was that "in" search is looping through all items, and that will occur inside the outer loop, hence results in O(n^2), but it turns out that "in" search is O(1) as mates mentioned here. – Tarreq May 21 '20 at 20:19
  • I figured that out, but I thought it was suspicious that your question was specifically about `key**2`. – Barmar May 21 '20 at 20:20
  • And Googling could have answered your question about the complexity of `in`. – Barmar May 21 '20 at 20:21
  • @Barmar Just wanted to mention, that post was closed as "duplicate" referring to a "python" question, not a Javascript question? It might be the same yes, but also it might happen that complexity and implementation differs from one language to another! right? – Tarreq May 21 '20 at 20:24
  • Oops, got confused about the language, sorry. – Barmar May 21 '20 at 20:25
  • https://stackoverflow.com/questions/7700987/performance-of-key-lookup-in-javascript-object – Barmar May 21 '20 at 20:26

2 Answers2

3

A JavaScript object is effectively a hash table, so looking up a key is O(1).

The total algorithm therefore is O(n).

Buh Buh
  • 7,051
  • 1
  • 31
  • 58
1

I would suspect that the in is not looping through all the items, but works like a hashtable. So I would say its O(n).