Skip to content

Instantly share code, notes, and snippets.

@indranil32
Created August 30, 2019 17:09
Show Gist options
  • Save indranil32/a2f3e028e399e4734161cf2a7255e733 to your computer and use it in GitHub Desktop.
Save indranil32/a2f3e028e399e4734161cf2a7255e733 to your computer and use it in GitHub Desktop.
o(n) implementation of two sum for sorted array
def arr2 = [1,3,4,5,9]
def sum = 16
def twoSum(arr, sum) {
if (arr[0] > sum) return;
if (arr[1] > sum || arr[1] + arr[0] > sum) return;
int i = 0;
int j = arr.size() -1
for ( ; i < j ; ) {
if ((arr[i] + arr[j]) > sum) {
j--;
} else if ((arr[i] + arr[j]) < sum){
i++;
} else {
println "found"
return;
}
}
}
twoSum(arr2, sum)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment