public class TwoPointerSum { public static void main(String[] args) { int[] arr = {1, 2, 3, 7, 8, 9}; int left = 0, right = arr.length - 1; boolean found = false; while (left < right) { int sum = arr[left] + arr[right]; if (sum == 10) { found = true; break; } else if (sum < 10) { left++; } else { right--; } } System.out.println(found); } }
The code uses two pointers starting at the ends of the sorted array. It checks pairs: (1,9) sums to 10, so it sets found to true and breaks the loop.
public class TwoPointerSwap { public static void main(String[] args) { int[] arr = {5, 3, 8, 6, 2}; int left = 0, right = arr.length - 1; while (left < right) { if (arr[left] % 2 == 0) { left++; } else if (arr[right] % 2 != 0) { right--; } else { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } for (int num : arr) { System.out.print(num + " "); } } }
The code moves left pointer forward if element is even, right pointer backward if element is odd. Otherwise, it swaps the odd on left with even on right. Swaps: 5↔2 to [2,3,8,6,5], then 3↔6 to [2,6,8,3,5].
Merging two sorted arrays efficiently uses two pointers, each pointing to the current element in each array, to build a merged sorted array.
public class TwoPointerError { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int left = 0, right = arr.length; while (left < right) { System.out.print(arr[left] + " "); left++; } } }
There is no error. right is arr.length (5), but while (left < right) prints arr[left] (0-4) then left++, so it correctly prints '1 2 3 4 5 ' without accessing arr[5].
Option B correctly initializes pointers and moves them based on whether the sum is greater or less than zero. It uses left < right and adjusts pointers properly.
