15% off all plans & roadmaps Use code

See plans

Combinations

Updated

TL;DR: You must list every group of k numbers from 1 to n, where order inside a group does not matter. Build each group one number at a time, and cut off any branch that can no longer reach size k.

Problem

You get two integers, n and k. List every group of k distinct numbers chosen from the values 1 through n. Two groups hold the same numbers only when they match, so order inside a group does not matter. Return the groups in any order.

Example 1

Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation: Picking 2 numbers out of 4 gives 6 groups. The group [2,1] is the same as [1,2], so it appears only once.

Example 2

Input: n = 1, k = 1
Output: [[1]]
Explanation: Picking 1 number out of 1 gives one group.

Constraints

  • 1 <= n <= 20
  • 1 <= k <= n

Constraints that matter

  • n up to 20 makes 2^n about one million, which is fast enough to enumerate, but most of those subsets have the wrong size.
  • The answer can hold C(20, 10) = 184,756 lists, so the output size sets the floor for any correct method.
  • k of at least 1 means the empty group is never an answer, so a size check can serve as the base case.
  • k at most n guarantees that at least one group exists, so the search always has something to find.

View on LeetCode

Hints

Hint 1

The answer is a list of groups, and each group is a set of numbers.

Hint 2

Treat every subset of 1 through n as a candidate.

Solution

Intuition

The answer is a list of groups, and each group is a set of numbers. Treat every number from 1 to n as a yes or no decision: take it into the current group, or leave it out. That is the subsets (include/exclude) pattern. Backtracking walks those choices, and it undoes each one before trying the next.

Picture a row of people you walk past once, left to right, choosing whether each one joins a team of k. The team sheet is the current list, and erasing the last name is the undo step before you try leaving that person out.

Order is the trap. If each step could pick any unused number, the search would produce both [1,2] and [2,1]. Walking the numbers in increasing order fixes that. Every group then has exactly one path, which takes its smallest number first.

Pruning keeps the search small. Once a group holds k numbers, you record it and stop. If the numbers still ahead cannot fill the missing slots, you cut that branch. Those two checks mean every node you visit still leads to at least one answer.

Watch the pattern animation

Worked example

Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation: Each group picks two of the four numbers. Groups are written in increasing order, so [2,1] never appears next to [1,2]. The six groups are every pair you can form from 1 to 4.

Approach 1: Brute force over all bitmasks

Treat every subset of 1 through n as a candidate. There are 2^n subsets, and a bitmask can encode each one, with bit i meaning number i + 1 is present. Keep only the masks that have exactly k bits set.

This is correct, but it builds subsets of every size. For n = 20 and k = 2, only 190 of the 1,048,576 masks survive the filter.

Steps

  1. Loop mask from 0 to 2^n - 1.
  2. Count the set bits in mask.
  3. If the count is not k, skip this mask.
  4. Read the bits. Bit i set means number i + 1 belongs to the group.
  5. Append that group to the result.
  6. Return the result.

Dry run

Masks 0 through 15 cover every subset of {1, 2, 3, 4}. Only masks with exactly two set bits pass the filter.

  • Mask 3 (binary 0011) gives [1,2].
  • Mask 5 (binary 0101) gives [1,3].
  • Mask 6 (binary 0110) gives [2,3].
  • Mask 9 (binary 1001) gives [1,4].
  • Mask 10 (binary 1010) gives [2,4].
  • Mask 12 (binary 1100) gives [3,4].

The six groups match the expected output, although the order differs.

Complexity

TimeO(n * 2^n)
SpaceO(n) extra, plus the output

Let n be the range size. The loop runs 2^n times, and each pass checks up to n bits to build a group, so the work is O(n * 2^n). The output holds C(n, k) groups of length k, which is at most n * 2^n, so storing the answer does not change the bound. Beyond the output, the code keeps one group of length at most n.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        result = []
        # every mask from 0 to 2^n - 1 is one subset of 1..n
        for mask in range(1 << n):
            # keep only subsets of size k
            if bin(mask).count('1') != k:
                continue
            # bit i set means number i + 1 is in the subset
            combo = [i + 1 for i in range(n) if (mask >> i) & 1]
            result.append(combo)
        # masks are not visited in lexicographic order, so sort the groups
        result.sort()
        return result

The Subsets (Include/Exclude) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Subsets (Include/Exclude)

Part of Backtracking Patterns

Approach 2: Include/exclude backtracking with pruningOptimalSubsets (Include/Exclude)

What is slow in the bitmask version: it builds every subset, then throws away most of them, and it keeps enumerating past the point where a group already has k numbers. The insight that fixes it: grow one group as you go, decide each number in increasing order, stop at size k, and skip any exclude branch that cannot fill the missing slots.

At index i you choose either to include i, which appends it and recurses, or to exclude i, which only recurses. Before excluding, check that the n - i numbers after i can still supply k - size values. If they cannot, the branch is dead, and you skip it.

Why it is correct. Each group of k numbers has exactly one path, because numbers are only added in increasing order, so no group is produced twice and none is missed. A skipped exclude branch only happens when the numbers left cannot fill the missing slots, so that branch holds no valid group. So every group stays reachable at every step, and the search returns all of them and only them.

Steps

  1. Start with index 1 and an empty current list.
  2. If current has k numbers, copy it into the result and return.
  3. If index is greater than n, return.
  4. Append index to current and recurse on index + 1.
  5. Remove the last number from current to undo the include.
  6. If n - index is at least k - len(current), recurse on index + 1 without index. Otherwise skip this branch.

Dry run

Each row is one call. The current column shows the list before the action runs.

StepCall indexcurrent before actionAction
11[]include 1
22[1]include 2, size is 2, record [1,2]
32[1]undo, check 2 >= 1 passes, exclude 2
43[1]include 3, record [1,3]
53[1]undo, check 1 >= 1 passes, exclude 3
64[1]include 4, record [1,4]
74[1]undo, check 0 >= 1 fails, prune
81[]undo, check 3 >= 2 passes, exclude 1
92[]include 2
103[2]include 3, record [2,3]
113[2]undo, check 1 >= 1 passes, exclude 3
124[2]include 4, record [2,4]
134[2]undo, check 0 >= 1 fails, prune
142[]undo, check 2 >= 2 passes, exclude 2
153[]include 3
164[3]include 4, record [3,4]
174[3]undo, check 0 >= 1 fails, prune
183[]undo, check 1 >= 2 fails, prune

The recorded groups are [1,2], [1,3], [1,4], [2,3], [2,4], [3,4]. That matches the example output. Rows 7, 13, 17 and 18 show the pruning check cutting dead branches.

Complexity

TimeO(n * C(n, k))
SpaceO(n)

Let n be the range size, and let C(n, k) be the number of answers. Each call either records a group or branches on a number. The pruning check guarantees that every visited call still has a valid completion, so each call lies on a path from the root to one of the C(n, k) answers.

A path has at most n + 1 calls, which gives at most (n + 1) * C(n, k) calls. Each call does constant work apart from the copy at a leaf, which costs O(k) and stays inside the same bound. The recursion depth is at most n + 1, and the current list never holds more than k values, so extra space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        result = []
        current = []

        def backtrack(index: int) -> None:
            # a full combination is recorded as a copy
            if len(current) == k:
                result.append(current[:])
                return
            if index > n:
                return
            # include index
            current.append(index)
            backtrack(index + 1)
            current.pop()
            # exclude index only if enough numbers remain after it
            if n - index >= k - len(current):
                backtrack(index + 1)

        backtrack(1)
        return result

Common mistakes

  • result.append(current) in Python or result.add(current) in Java stores a reference to the shared list. Backtracking empties that list later, so every saved group ends up empty. Store a copy with current[:] in Python or current.clone() in Java.
  • An include with no matching undo, such as current.append(index) without the current.pop() after the recursive call. The list keeps stale numbers, and later groups come out too long. Undo the include right after the recursive call returns.
  • Using n - index > k - len(current) in the exclude check. With n = 3 and k = 2 at index 1 and an empty list, the strict comparison gives 2 > 2, which is false, so the branch is pruned and [2,3] is lost. Use >=.
  • Checking index > n before len(current) == k. A group that finishes with n as its last number reaches index n + 1 with a full list, and the early return drops it. Check the size first.
  • Starting the recursion at 1 each time instead of at index + 1. That produces both [1,2] and [2,1], so the output has duplicates and the wrong count. The start index must only move forward.

Edge cases

  • n = 1 and k = 1 returns the single group [[1]].
  • k = n, such as n = 5 and k = 5, returns exactly one group, [1,2,3,4,5].
  • k = 1 returns n single-element groups in increasing order.
  • n = 20 and k = 10 returns 184,756 groups. Each group must be an independent copy, not a reference to the shared list.
  • n = 3 and k = 2 must include [2,3]. A strict pruning check fails this case, so test it.

Follow-ups interviewers ask

Can the groups come out in lexicographic order?
The current method already does this. It tries include before exclude, and the index only moves forward, so the smallest next number always comes first. For n = 4 and k = 2 the output is [1,2], [1,3], [1,4], [2,3], [2,4], [3,4], which is lexicographic.
Can you generate the groups without recursion?
Yes. Keep the current group as an array of k values, and step to the next group each time. Find the rightmost value that can still increase, raise it by one, and reset every value after it to consecutive numbers. Each step costs O(k), and you stop when the first value passes n - k + 1.
What if the groups do not fit in memory?
Stop collecting them in a list and yield each group as soon as it completes. In Python, turn the recursion into a generator that yields a copy at each full group. Memory then depends on the recursion depth and one group, which is O(n).

Combinations FAQ

What is the time complexity of Combinations?

The pruned backtracking runs in O(n * C(n, k)) time, where C(n, k) is the number of answers. The bitmask brute force runs in O(n * 2^n) time. The complexity section above counts the work behind both bounds.

Why use backtracking for Combinations?

Each group is a path of include and exclude decisions. Backtracking walks those paths in order and undoes each decision, so it never rebuilds a list from scratch. The pruning check stops it from visiting paths that cannot reach size k.

Can Combinations be solved in O(1) extra space?

No, not in the usual sense. The method has to hold a group of k numbers at once, so the extra space is at least O(k). The recursive version also uses O(n) for the call stack.

Why does my Python result contain empty lists?

You appended the shared current list instead of a copy. Backtracking empties that list before the function returns, so every saved entry ends up empty. Append current[:] when you record a group.

How is Combinations different from Permutations?

Combinations ignore order, so the start index only moves forward. Permutations treat [1,2] and [2,1] as different, so every unused number is a valid next choice. That changes the search tree and the number of results.

Asked at

See which companies ask this — Pro

Practise it