looking for two indices whose value add to target n
o(n^2)
def quad_find(s, n):
slen = len(s)
for i in range(slen):
for j in range(slen-1):
if s[i] + s[j+1] == n:
return (i, j+1)
return None
In the provided Python function, 's' represents a list and 'n' represents the target value.
o(n)
def linear_find(s, n):
dict = {}
for i in range(len(s)):
if s[i] in dict:
return (i, dict[s[i]]) # s[i] contains the other index
else:
complement = n - s[i]
dict[complement] = i
return None
In our linear_find
function, we commence by initializing an empty dictionary, which plays a critical role as a hashmap. This hashmap is used to store indices of 'complementary' elements—these are elements which, when added to another, would equal the target sum 'n'.