Combinations - Problem

Imagine you're organizing a team selection process where you need to pick exactly k people from a group of n candidates numbered from 1 to n. Your task is to generate all possible team combinations that can be formed.

Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. The order of combinations in your result doesn't matter, but each combination should contain unique numbers.

Example: If n=4 and k=2, you could form teams like [1,2], [1,3], [1,4], [2,3], [2,4], [3,4] - that's 6 different combinations!

Input & Output

example_1.py โ€” Basic Combination
$ Input: n = 4, k = 2
โ€บ Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
๐Ÿ’ก Note: All possible ways to choose 2 numbers from [1,2,3,4]. We get C(4,2) = 6 combinations total.
example_2.py โ€” Single Element
$ Input: n = 1, k = 1
โ€บ Output: [[1]]
๐Ÿ’ก Note: Only one way to choose 1 number from [1] - the combination [1] itself.
example_3.py โ€” Larger Set
$ Input: n = 5, k = 3
โ€บ Output: [[1,2,3],[1,2,4],[1,2,5],[1,3,4],[1,3,5],[1,4,5],[2,3,4],[2,3,5],[2,4,5],[3,4,5]]
๐Ÿ’ก Note: All possible ways to choose 3 numbers from [1,2,3,4,5]. We get C(5,3) = 10 combinations total.

Constraints

  • 1 โ‰ค k โ‰ค n โ‰ค 20
  • k cannot exceed n (you can't choose more items than available)
  • Output size grows exponentially - C(n,k) can be up to C(20,10) = 184,756

Visualization

Tap to expand
Team Building Process (n=4, k=2)Step 1: SetupTeam: []Available: [1,2,3,4]Step 2: Pick FirstTeam: [1]Available: [2,3,4]Step 3: CompleteTeam: [1,2]โœ“ Save resultStep 4: BacktrackTeam: [1]Try next: [1,3]Complete Results Tree[1,2][1,3][1,4][2,3][2,4][3,4]โœ“ All 6 combinations found systematically!๐Ÿ’ก Key Strategy:Always choose from remaining candidates in ascending order to avoid duplicates and ensure systematic coverage.
Understanding the Visualization
1
Start Empty
Begin with an empty team and list of all available players [1,2,3,4]
2
Fill Positions
For position 1, try player 1, then explore all possibilities for position 2
3
Complete & Backtrack
When team is full (k players), save it. Then backtrack and try next player
4
Systematic Exploration
Continue until all possible team combinations are found
Key Takeaway
๐ŸŽฏ Key Insight: Backtracking with ordered selection ensures we generate all unique combinations exactly once, while pruning optimizations eliminate impossible paths early for better performance.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
52.0K Views
High Frequency
~15 min Avg. Time
1.4K 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