def hasPairWithSum(arr,target):
for i in range(len(arr)):
if ((target-arr[i]) in arr[i+1:]):
return True
return False
In python, is time complexity for this function O(n) or O(n^2), in other words 'if ((target-arr[i]) in arr[i+1:])' is this another for loop or no? Also what about following function, is it also O(n^2), if not why:
def hasPairWithSum2(arr,target):
seen = set()
for num in arr:
num2 = target - num
if num2 in seen:
return True
seen.add(num)
return False
Thanks!
if ((target-arr[i]) in arr[i+1:])is another loop. It needs to compare each element of the listarr[i+1:]. A way to avoid this is to create a set, dictionary, or some other data structure that allows constant time inclusion tests.s = set(arr)and usedin sinstead ofin arr[i+1:]it would be O(n)