InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Backtracking

Combinations

medium Original ↗ 00:00

Problem

Given two integers n and k, return all combinations of k distinct numbers chosen from the range 1..n (inclusive). Each combination is a set — [1,2] and [2,1] are the same combination and must appear only once. You may return the combinations, and the numbers inside each one, in any order.

Examples

  • n = 4, k = 2[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] — all C(4,2) = 6 pairs.
  • n = 1, k = 1[[1]] — the only choice.
  • n = 5, k = 5[[1,2,3,4,5]] — choosing everything leaves exactly one combination.

Constraints

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

The output itself can hold C(20,10) ≈ 184,756 combinations of length 10 — the answer size is exponential, so the goal is generating each combination exactly once with as little wasted exploration as possible.

Think about it first

Hint 1 How do you avoid emitting both [1,2] and [2,1]? Decide on a canonical form — say, strictly increasing — and only ever generate that form.
Hint 2 Build the combination left to right: after placing the number v, the next slot may only use numbers greater than v. What two parameters does the recursion need?
Hint 3 Prune hopeless branches by counting: if you still need m more numbers but fewer than m candidates remain above your current start, no leaf below can succeed — the loop bound can encode this directly. Alternatively, think per number: 1..n each either joins the combination or doesn't, with a budget of k joins.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug