I was doing a programming exercise on Leetcode (500 Keyboard Row) and I came across set.issubset() in discussions. Upon comparing with my own answer, here's an interesting finding:
1)
def checkWord(self, word):
r1 = 'qwertyuiop'
r2 = 'asdfghjkl'
r3 = 'zxcvbnm'
row = 0
for idx, ch in enumerate(word):
if idx == 0:
row = 1 if ch in r1 else 2 if ch in r2 else 3
continue
coming_row = 1 if ch in r1 else 2 if ch in r2 else 3
if row != coming_row:
return False
return True
If I submit with this, I get a runtime of 40ms
2)
def checkWord(self, word):
r1 = 'qwertyuiop'
r2 = 'asdfghjkl'
r3 = 'zxcvbnm'
return set(word).issubset(r1) or set(word).issubset(r2) or set(word).issubset(r3)
If I use issubset(), I get a runtime of 36ms, which beats 94.87% of all submissions.
3) So I thought, hmmm, what's the difference with this piece? According to a question I found on this topic The complextiy of Python issubset(), the time complexity of method 2) should be O(len(word)), which I believe should be the same with this piece:
def checkWord(self, word):
r1 = set('qwertyuiop')
r2 = set('asdfghjkl')
r3 = set('zxcvbnm')
row = 0
for idx, ch in enumerate(word):
if idx == 0:
row = 1 if ch in r1 else 2 if ch in r2 else 3
continue
coming_row = 1 if ch in r1 else 2 if ch in r2 else 3
if row != coming_row:
return False
return True
However, the runtime of this is 32ms and beats 100% of all py3 submissions... Why is issubset() slower than this? Thanks!