TheAlgorithms/Java · error · IllegalArgumentException

The number of pairs of parentheses cannot be negative

Error message

The number of pairs of parentheses cannot be negative

What it means

Thrown by ParenthesesGenerator.generateParentheses(n) when n is negative. The generator enumerates all well-formed strings of n pairs of parentheses, which requires n >= 0. The generator accepts n == 0 (returns a list containing the empty string via the helper) and rejects any negative count.

Source

Thrown at src/main/java/com/thealgorithms/backtracking/ParenthesesGenerator.java:22

import java.util.List;

/**
 * This class generates all valid combinations of parentheses for a given number of pairs using backtracking.
 */
public final class ParenthesesGenerator {
    private ParenthesesGenerator() {
    }

    /**
     * Generates all valid combinations of parentheses for a given number of pairs.
     *
     * @param n The number of pairs of parentheses.
     * @return A list of strings representing valid combinations of parentheses.
     * @throws IllegalArgumentException if n is less than 0.
     */
    public static List<String> generateParentheses(final int n) {
        if (n < 0) {
            throw new IllegalArgumentException("The number of pairs of parentheses cannot be negative");
        }
        List<String> result = new ArrayList<>();
        generateParenthesesHelper(result, "", 0, 0, n);
        return result;
    }

    /**
     * Helper function for generating all valid combinations of parentheses recursively.
     *
     * @param result  The list to store valid combinations.
     * @param current The current combination being formed.
     * @param open    The number of open parentheses.
     * @param close   The number of closed parentheses.
     * @param n       The total number of pairs of parentheses.
     */
    private static void generateParenthesesHelper(List<String> result, final String current, final int open, final int close, final int n) {
        if (current.length() == n * 2) {
            result.add(current);

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Ensure n >= 0; if n == 0 is a valid 'generate nothing' case, handle it explicitly rather than passing a negative.
  2. Validate/parse input and reject negative values before calling.
  3. Clamp n to 0 if a non-negative fallback is acceptable.

Example fix

// before
ParenthesesGenerator.generateParentheses(parsedN);  // throws if parsedN < 0

// after
int n = Math.max(0, parsedN);
ParenthesesGenerator.generateParentheses(n);
Defensive patterns

Strategy: validation

Validate before calling

if (n < 0) throw new IllegalArgumentException("n must be >= 0");
ParenthesesGenerator.generateParentheses(n);

Type guard

public static boolean validPairCount(int n) {
    return n >= 0;
}

Try / catch

try {
    return ParenthesesGenerator.generateParentheses(n);
} catch (IllegalArgumentException e) {
    return Collections.emptyList();
}

Prevention

When it happens

Trigger: Calling `generateParentheses(-1)` or `generateParentheses(-3)`. The guard `n < 0` rejects negatives; n == 0 is valid.

Common situations: n read from input that defaults to -1 when missing; n derived from a subtraction that underflows; passing a count before validating the source data.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/8e225d2a71a7bd43. Report an issue: GitHub.