1+ # Pair with Target Sum (easy) 
2+ # Given an array of sorted numbers and a target sum, find a pair in the array whose sum is equal to the given target. 
3+ 4+ # Write a function to return the indices of the two numbers (i.e. the pair) such that they add up to the given target. 
5+ 6+ # Input: [1, 2, 3, 4, 6], target=6 
7+ # Output: [1, 3] 
8+ # Explanation: The numbers at index 1 and 3 add up to 6: 2+4=6 
9+ 10+ def  pair_with_targetsum (arr , target_sum ):
11+  left , right  =  0 , len (arr ) -  1 
12+  while (left  <  right ):
13+  current_sum  =  arr [left ] +  arr [right ]
14+  if  current_sum  ==  target_sum :
15+  return  [left , right ]
16+ 17+  if  target_sum  >  current_sum :
18+  left  +=  1  # we need a pair with a bigger sum 
19+  else :
20+  right  -=  1  # we need a pair with a smaller sum 
21+  return  [- 1 , - 1 ]
22+ 23+ def  pair_with_targetsum2 (arr , target_sum ):
24+  nums  =  {} # to store numbers and their indices 
25+  for  i , num  in  enumerate (arr ):
26+  if  target_sum  -  num  in  nums :
27+  return  [nums [target_sum  -  num ], i ]
28+  else :
29+  nums [arr [i ]] =  i 
30+  return  [- 1 , - 1 ]
31+ 32+ def  main ():
33+  print (pair_with_targetsum ([1 , 2 , 3 , 4 , 6 ], 6 ))
34+  print (pair_with_targetsum ([2 , 5 , 9 , 11 ], 11 ))
35+  print ('---' )
36+  print (pair_with_targetsum2 ([1 , 2 , 3 , 4 , 6 ], 6 ))
37+  print (pair_with_targetsum2 ([2 , 5 , 9 , 11 ], 11 ))
38+ 39+ main ()
0 commit comments