Skip to content

Commit 8b19b87

Browse files
authored
fix(dynamicprogramming): handle n=0 and negative inputs safely in CatalanNumber (#7731)
1 parent 0a76bf8 commit 8b19b87

2 files changed

Lines changed: 16 additions & 0 deletions

File tree

‎src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,16 @@ private CatalanNumber() {
2121
* n > 50, BigInteger class should be used instead long
2222
*
2323
* @return catalanArray[n] the nth Catalan number
24+
* @throws IllegalArgumentException if n is negative
2425
*/
2526
static long findNthCatalan(int n) {
27+
if (n < 0) {
28+
throw new IllegalArgumentException("n must be non-negative");
29+
}
30+
if (n <= 1) {
31+
return 1;
32+
}
33+
2634
// Array to store the results of subproblems i.e Catalan numbers from [1...n-1]
2735
long[] catalanArray = new long[n + 1];
2836

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,22 @@
11
package com.thealgorithms.dynamicprogramming;
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
45

56
import org.junit.jupiter.api.Test;
67

78
public class CatalanNumberTest {
89

910
@Test
1011
public void testCatalanNumber() {
12+
assertEquals(1, CatalanNumber.findNthCatalan(0));
13+
assertEquals(1, CatalanNumber.findNthCatalan(1));
1114
assertEquals(42, CatalanNumber.findNthCatalan(5));
1215
assertEquals(16796, CatalanNumber.findNthCatalan(10));
1316
}
17+
18+
@Test
19+
public void testNegativeInput() {
20+
assertThrows(IllegalArgumentException.class, () -> CatalanNumber.findNthCatalan(-1));
21+
}
1422
}

0 commit comments

Comments
 (0)