Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

public static int twoSum(int[] arr) – returns the number of pairs of unique valu

ID: 3742573 • Letter: P

Question

public static int twoSum(int[] arr) – returns the number of pairs of unique values whose sum equals zero. Assume that the input array is sorted in ascending order and the values stored in the array are unique.

Example: If arr = {-13, -9, -2, 0, 1, 2, 4, 9, 11} then there are two pairs whose sum is zero. (-9 + 9 = 0 and -2 + 2 = 0).

Each array element can be inspected at most one time. Therefore, you cannot use a nested loop. Stop iterating once the method determines there are no more remaining pairs that sum to zero.

Set an int variable called numPairs to 0.

Set an int variable called left to 0 and an int variable called right to arr.length – 1.

Iterate if (i) left < right and (ii) the values stored at left and right have different signs.

If the values stored at left and right have a sum = 0 then increase numPairs by 1, increase left by 1 and decrease right by 1.

If the absolute value stored at left is greater than the value stored at right then increase left by 1. Otherwise, decrease right by 1.

public static int[] convertToOneD(int[][] arr) – returns a one-dimensional int array that stores the values contained in arr. The length of the array returned by the method should be equal to the number of int values stored in arr. The returned array should first contain the values stored in row 0, then the values stored in row 1, etc. Do not use a nested loop.

Hint: Use the length property and the System.arraycopy method.

Explanation / Answer

class Main {

public static int twoSum(int[] arr)

{

int numPairs = 0, left = 0, right = arr.length - 1;

while(left < right && arr[left] < 0 && arr[right] > 0)

{

if(arr[left] + arr[right] == 0)

{

numPairs++;

left++;

right--;

}

else if(-arr[left] > arr[right])

left++;

else

right--;

}

return numPairs;

}

public static void main(String[] args) {

System.out.println(twoSum(new int[]{-13, -9, -2, 0, 1, 2, 4, 9, 11}));

}

}

/* OUTPUT: 2*/

// Note: One question at a time please -- Policy of Chegg