Combinations
Combinations is a Medium Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Backtracking Patterns pattern, in the Subsets (Include/Exclude) subpattern.
Problem statement
Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].
You may return the answer in any order.
Example 1:
Input: n = 4, k = 2 Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] Explanation: There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.
Example 2:
Input: n = 1, k = 1 Output: [[1]] Explanation: There is 1 choose 1 = 1 total combination.
Constraints:
- 1 <= n <= 20
- 1 <= k <= n
Topics and companies
Topics: Backtracking.
Reported in interviews at Facebook, Amazon.
How to practise Combinations on Thita.ai
Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(C(n, k) * k), where C(n, k) is the number of combinations. Each combination is built in O(k) time. time and O(C(n, k) * k), for storing all combinations. The recursion stack uses O(k) space. space.
Open Combinations in the code editor, or read the Combinations editorial for a worked solution with its approach and complexity analysis.
Where Combinations sits in the DSA pattern sheet
- Backtracking Patterns pattern guide
- Subsets (Include/Exclude) subpattern
- The full DSA patterns sheet
- All coding practice problems
Problems related to Combinations
Other problems that use the same Subsets (Include/Exclude) and Backtracking Patterns techniques:
- Letter Combinations of a Phone Number — Medium, same subpattern
- Subsets — Medium, same subpattern
- Subsets II — Medium, same subpattern
- Check if Word Can Be Placed In Crossword — Medium, same pattern
- Combination Sum — Medium, same pattern
- Combination Sum II — Medium, same pattern
Preparing your workspace
Progress is saved as you study.