Combination Generator with Constraints - Problem
Given a list of N items and a number K, generate all possible combinations of exactly K items from the list.
However, there's a twist: you're also given a list of forbidden pairs - certain items that cannot appear together in the same combination.
For example, if items [1, 2] form a forbidden pair, then any combination containing both item 1 and item 2 should be excluded from the result.
Input:
items: Array of N distinct items (integers)k: Number of items to select in each combinationforbidden: Array of forbidden pairs, where each pair is represented as[item1, item2]
Output: Return all valid combinations as a 2D array, where each sub-array contains exactly K items and no forbidden pairs appear together.
Input & Output
Example 1 — Basic Case with Forbidden Pairs
$
Input:
items = [1,2,3,4], k = 3, forbidden = [[1,3]]
›
Output:
[[1,2,4],[2,3,4]]
💡 Note:
All 3-combinations are [1,2,3], [1,2,4], [1,3,4], [2,3,4]. We exclude [1,2,3] and [1,3,4] because they contain the forbidden pair [1,3].
Example 2 — Multiple Forbidden Pairs
$
Input:
items = [1,2,3,4], k = 2, forbidden = [[1,2],[3,4]]
›
Output:
[[1,3],[1,4],[2,3],[2,4]]
💡 Note:
All 2-combinations are [1,2], [1,3], [1,4], [2,3], [2,4], [3,4]. We exclude [1,2] and [3,4] due to forbidden pairs.
Example 3 — No Valid Combinations
$
Input:
items = [1,2], k = 2, forbidden = [[1,2]]
›
Output:
[]
💡 Note:
The only possible 2-combination is [1,2], but it's forbidden, so no valid combinations exist.
Constraints
- 1 ≤ items.length ≤ 20
- 1 ≤ k ≤ items.length
- 0 ≤ forbidden.length ≤ 50
- forbidden[i].length = 2
- All items are distinct
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code