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 combination
  • forbidden: 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
INPUT DATABACKTRACKINGVALID RESULTS1234Items: [1,2,3,4]Choose k=3 itemsForbidden Pairs[1,3] cannot appear togetherMust exclude combinationscontaining both1Start: try item 12Check constraints for item 1+33Prune: [1,3] forbidden!4Backtrack and continueKey Steps:1. Build combinations incrementally2. Check constraints before adding3. Prune invalid branches early4. Save valid k-combinationsValid Combinations[1,2,4] and [2,3,4][1,2,4][2,3,4]✓ No forbidden pairs✓ Each has exactly k=3 itemsKey Insight:Check constraints while building combinations (backtracking) rather than afterTutorialsPoint - Combination Generator with Constraints | Backtracking Approach
Asked in
Google 25 Amazon 18 Microsoft 15 Apple 12
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen