Algorithm to return all combinations of k elements from n
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.
Introduction
Combinatorial problems are an integral part of computer science and mathematics. One of the classic problems is generating all combinations of k elements from a set of n elements. This task is not only essential in mathematical computations but also finds applications in areas like data analysis, probability theory, and algorithm design.
Understanding Combinations
In combinatorics, a combination is a selection of items without considering the order. For instance, choosing 2 elements from a set {1, 2, 3} will yield combinations {1,2}, {1,3}, and {2,3}. The mathematical notation for combinations is given by the binomial coefficient:
The number of combinations is often written as "n choose k" and equals n! ÷ (k! × (n - k)!), where n is the total number of elements, k is the number chosen, and ! denotes factorial.
Algorithm to Generate Combinations
There are multiple ways to generate combinations programmatically, but a recursive approach provides an elegant and straightforward solution. Here’s a step-by-step breakdown of the algorithm:
Recursive Backtracking Approach
Backtracking is a common approach to solving combinatorial problems. The idea is to build combinations incrementally and explore possibilities using recursion.
- Base Case: If the size of the current combination is equal to
k, add it to the result list. - Recursion: For each element, attempt to construct combinations by including it and recursively generating combinations of the rest.
- Avoid Repetition: Ensure not to reuse elements by starting from the next element in the list whenever you include an element in the current combination.
Pseudocode
Here's the pseudocode for generating all combinations of k elements from n:
Example
Let's illustrate this with an example. Suppose we need to generate combinations of 2 elements from the set {A, B, C}.
- Begin with the empty set
{}. - Choose
A, construct combinations:{A,B},{A,C}. - Choose
B, consider subsequent elements:{B,C}.
Analysis of the Recursive Approach
Time Complexity
The time complexity of generating combinations is on the order of (number of combinations) × k. Here C(n, k)—the count of distinct combinations—multiplies by k because each combination requires copying or outputting k elements.
Space Complexity
The space complexity is O(k + n), where k accounts for the current combination and n comes from the recursive call stack.
Comparative Summary
The table below offers a comparative summary of key points related to this algorithm:
| Aspect | Description |
| Approach | Recursive Backtracking |
| Efficiency | Time: O(C(n, k) × k)
Space: O(k + n) |
| Example | Input: {A, B, C}, k = 2
Output: {A,B}, {A,C}, {B,C} |
| Applications | Data Analysis, Probability Calculations, Algorithm Design |
| Benefits | Intuitive and simple recursive solution Easily adaptable for minor constraint variations |
Additional Details
Iterative Approach
An iterative approach using bitwise operations or nested loops is another way to generate combinations. This method can be useful in non-recursive environments or when system recursion limits are a constraint.
Variations
- Combinations with Repetitions: Choose
kelements where each element can be reused. - Permutations: Unlike combinations, order matters, allowing the generation of permutations.
Conclusion
Generating all combinations of k elements from n is a fundamental exercise in combinatorics and algorithm design. Whether using recursive backtracking for its simplicity and elegance, or iterative approaches for specific constraints, mastering this problem is critical for algorithmic capability and deeper mathematical understanding. By efficiently generating combinations, numerous mathematical and practical challenges can be solved effectively.
Related reading
- Algorithm to rotate an array in linear time
- Algorithm to search for a list of words in a text
- Algorithm to select a set of numbers to reach a minimum total
- Algorithm to select a single, random combination of values?
- Algorithm to solve the points of a evenly-distributed / even-gaps spiral?
- Algorithm to sort pairs of numbers
- Algorithm to select Player with max points but with a given cost
- Algorithm to share/settle expenses among a group

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.