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 7
7
* <p>
8
8
* Link: https://www.geeksforgeeks.org/two-pointers-technique/
9
9
*/
10
- final class TwoPointers {
10
+ public final class TwoPointers {
11
+
11
12
private TwoPointers () {
12
13
}
13
14
14
15
/**
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.
17
17
*
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}
21
22
*/
22
23
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 ];
25
33
26
- while (i < j ) {
27
- int sum = arr [i ] + arr [j ];
28
34
if (sum == key ) {
29
35
return true ;
30
- } else if (sum < key ) {
31
- i ++;
36
+ }
37
+ if (sum < key ) {
38
+ left ++;
32
39
} else {
33
- j --;
40
+ right --;
34
41
}
35
42
}
36
43
return false ;
Original file line number Diff line number Diff line change 1
1
package com .thealgorithms .others ;
2
2
3
+ import static org .junit .jupiter .api .Assertions .assertEquals ;
3
4
import static org .junit .jupiter .api .Assertions .assertFalse ;
5
+ import static org .junit .jupiter .api .Assertions .assertThrows ;
4
6
import static org .junit .jupiter .api .Assertions .assertTrue ;
5
7
6
8
import org .junit .jupiter .api .Test ;
@@ -69,4 +71,10 @@ void testPairExistsAtEdges() {
69
71
int key = 9 ;
70
72
assertTrue (TwoPointers .isPairedSum (arr , key ));
71
73
}
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
+ }
72
80
}
You can’t perform that action at this time.
0 commit comments