Monday, December 2, 2019

Two-Pointer Method: Target Sum in Sorted Array

TargetSum

Two-Pointer Method: FInd Target Sum in Sorted Array

https://tp-iiita.quora.com/The-Two-Pointer-Algorithm

In [1]:
#
# Motivation Problem: Given a sorted array A having N integers. 
# You need to find any pair (i,j) having sum as given number X.
#

def sumX(arr, X):
    left = 0
    right = len(arr)-1
    while (left < right):
        if (arr[left] + arr[right] == X):
            return True
        elif (arr[left] + arr[right] > X):
            right-=1
        else:
            left+=1
    return False

test_list = [99,2,4,5,7,8,20]
test_list.sort()
print(test_list)

for target in range(5,13):
    print("target sum",target,"exists",sumX(test_list,target))
[2, 4, 5, 7, 8, 20, 99]
target sum 5 exists False
target sum 6 exists True
target sum 7 exists True
target sum 8 exists False
target sum 9 exists True
target sum 10 exists True
target sum 11 exists True
target sum 12 exists True