Refactor: simplify validation and improve backtracking cleanup (#7258)

### Summary
This PR makes small readability and maintainability improvements to the algorithm implementation.

### Changes
- Removed a redundant `n < 0` validation check since the method contract already ensures valid `n`
- Replaced `current.remove(current.size() - 1)` with `current.removeLast()` to better express backtracking intent

### Rationale
- Simplifies input validation without changing behavior
- Uses the `Deque` API to make the backtracking step clearer and less error-prone

### Impact
- No change in algorithm logic or time/space complexity
- Output remains identical

Co-authored-by: Swati Vusurumarthi <swativs869@gmail.com>
This commit is contained in:
swativ15
2026-02-06 03:37:11 +05:30
committed by GitHub
parent 249b88fea2
commit 3835c4822a

View File

@@ -20,8 +20,8 @@ public final class ArrayCombination {
* @throws IllegalArgumentException if n or k are negative, or if k is greater than n.
*/
public static List<List<Integer>> combination(int n, int k) {
if (n < 0 || k < 0 || k > n) {
throw new IllegalArgumentException("Invalid input: n must be non-negative, k must be non-negative and less than or equal to n.");
if (k < 0 || k > n) {
throw new IllegalArgumentException("Invalid input: 0 ≤ k ≤ n is required.");
}
List<List<Integer>> combinations = new ArrayList<>();
@@ -48,7 +48,7 @@ public final class ArrayCombination {
for (int i = start; i < n; i++) {
current.add(i);
combine(combinations, current, i + 1, n, k);
current.remove(current.size() - 1); // Backtrack
current.removeLast(); // Backtrack
}
}
}