File tree Expand file tree Collapse file tree 2 files changed +28
-13
lines changed
main/java/com/thealgorithms/others
test/java/com/thealgorithms/others Expand file tree Collapse file tree 2 files changed +28
-13
lines changed Original file line number Diff line number Diff line change 77 * <p>
88 * Link: https://www.geeksforgeeks.org/two-pointers-technique/
99 */
10- final class TwoPointers {
10+ public final class TwoPointers {
11+
1112 private TwoPointers () {
1213 }
1314
1415 /**
15- * Given a sorted array arr (sorted in ascending order), find if there exists
16- * any pair of elements such that their sum is equal to the key.
16+ * Checks whether there exists a pair of elements in a sorted array whose sum equals the specified key.
1717 *
18- * @param arr the array containing elements (must be sorted in ascending order)
19- * @param key the number to search
20- * @return {@code true} if there exists a pair of elements, {@code false} otherwise.
18+ * @param arr a sorted array of integers in ascending order (must not be null)
19+ * @param key the target sum to find
20+ * @return {@code true} if there exists at least one pair whose sum equals {@code key}, {@code false} otherwise
21+ * @throws IllegalArgumentException if {@code arr} is {@code null}
2122 */
2223 public static boolean isPairedSum (int [] arr , int key ) {
23- int i = 0 ; // index of the first element
24- int j = arr .length - 1 ; // index of the last element
24+ if (arr == null ) {
25+ throw new IllegalArgumentException ("Input array must not be null." );
26+ }
27+
28+ int left = 0 ;
29+ int right = arr .length - 1 ;
30+
31+ while (left < right ) {
32+ int sum = arr [left ] + arr [right ];
2533
26- while (i < j ) {
27- int sum = arr [i ] + arr [j ];
2834 if (sum == key ) {
2935 return true ;
30- } else if (sum < key ) {
31- i ++;
36+ }
37+ if (sum < key ) {
38+ left ++;
3239 } else {
33- j --;
40+ right --;
3441 }
3542 }
3643 return false ;
Original file line number Diff line number Diff line change 11package com .thealgorithms .others ;
22
3+ import static org .junit .jupiter .api .Assertions .assertEquals ;
34import static org .junit .jupiter .api .Assertions .assertFalse ;
5+ import static org .junit .jupiter .api .Assertions .assertThrows ;
46import static org .junit .jupiter .api .Assertions .assertTrue ;
57
68import org .junit .jupiter .api .Test ;
@@ -69,4 +71,10 @@ void testPairExistsAtEdges() {
6971 int key = 9 ;
7072 assertTrue (TwoPointers .isPairedSum (arr , key ));
7173 }
74+
75+ @ Test
76+ void isPairedSumShouldThrowExceptionWhenArrayIsNull () {
77+ IllegalArgumentException exception = assertThrows (IllegalArgumentException .class , () -> TwoPointers .isPairedSum (null , 10 ));
78+ assertEquals ("Input array must not be null." , exception .getMessage ());
79+ }
7280}
You can’t perform that action at this time.
0 commit comments