DSA AnimatorREVISION VIDEOS
← Back to problems
New

Combinations — LeetCode 77 video explanation

Given n and k, return all combinations of k numbers chosen from 1 to n. Order inside a combination does not matter.

Loading videos…

DSA Animator › DSA Revision › Backtracking › Combinations

Key moments in the Combinations video

0:03Problem0:12Example0:21Brute force0:27Key idea0:39Dry run0:55Code1:09Takeaway

What you will learn

Remember: increasing order avoids repeats. Prune when not enough numbers are left. The video solves Combinations (LeetCode 77, Medium) with the Backtracking + Pruning pattern from the Backtracking topic, and you can replay every step in the interactive Combinations animation.

Combinations video transcript

Problem

Given n and k, return all combinations of k numbers chosen from 1 to n. Order inside a combination does not matter.

Example

For n equal to 4 and k equal to 2, there are 6 combinations. They are 1 2, 1 3, 1 4, 2 3, 2 4 and 3 4.

Brute force

Generating every subset and keeping those of size k wastes work. Stop as soon as a path has k numbers.

Key idea

Choose numbers in increasing order, starting after the last one picked. When the path has k numbers, record it and return. Prune: if too few numbers are left to reach k, stop the loop early.

Dry run

Start with 1, then add 2, 3 and 4 in turn, recording 1 2, 1 3 and 1 4. Start with 2, recording 2 3 and 2 4. Start with 3, recording 3 4. Starting with 4 leaves no number after it, so that branch is pruned. There are 6 combinations.

Code

In code, if the path size equals k, add a copy and return. Loop i from start while enough numbers remain, which is the pruning bound. Choose, recurse with i plus 1, then un-choose, so it's O of k times n choose k.

Takeaway

Remember: increasing order avoids repeats. Prune when not enough numbers are left.

More Backtracking revision videos

← All 185 DSA revision videos