I was solving a hackerrank challenge.(in Python 3)
At one point I needed to sort a list and work with it.
(2 <= len(array) <= 10^5)
The list is containing unique integers.
I used arr.sort()
, but I was getting "Time limit exceeded" message
Then I found if I use set(arr)
, it runs fast and passes all test cases.
here's is my function for more clarification
def pairs(k, ar):
ar.sort()
c=0
for i in ar:
if i+k in ar:
c+=1
return c
This gets me "Time limit exceeded"
def pairs(k, ar):
ar=set(ar)
c=0
for i in ar:
if i+k in ar:
c+=1
return c
This one with set() runs faster. Why is this set() is faster than sort(). Don't they use same sorting algorithm?