40. Combination Sum II

Combination Sum II (LeetCode 40) 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 Combination Sum subpattern.

How to solve Combination Sum II

Combination Sum II is a Combination Sum problem, part of Backtracking Patterns. Find combinations that sum to target using backtracking. Handle reuse and duplicates.

Work towards the solution in these steps:

  1. Consider using backtracking to explore all potential combinations of numbers that sum up to the target.
  2. Sorting the candidates array first can help you efficiently skip duplicates and manage combination order.
  3. In your backtracking function, keep track of the current combination and the remaining target to decide when to stop or continue exploring.

The reference solution runs in O(2^n) time and O(k * n) space.

The Combination Sum II solution and editorial walks through the full approach with reference code.

Problem statement

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Each number in candidates may only be used once in the combination.

Note: The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8 Output: [ [1,1,6], [1,2,5], [1,7], [2,6] ]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5 Output: [ [1,2,2], [5] ]

Constraints:

- 1 <= candidates.length <= 100

- 1 <= candidates[i] <= 50

- 1 <= target <= 30

Topics and companies

Topics: Array, Backtracking.

Reported in interviews at Amazon, Uber, Microsoft, ByteDance.

How to practise Combination Sum II 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(2^n) time and O(k * n) space.

Open Combination Sum II in the code editor, or read the Combination Sum II editorial for a worked solution with its approach and complexity analysis.

Where Combination Sum II sits in the DSA pattern sheet

Problems related to Combination Sum II

Other problems that use the same Combination Sum and Backtracking Patterns techniques:

Combination Sum II FAQ

What is the LeetCode number of Combination Sum II?

Combination Sum II is LeetCode problem 40, rated Medium.

What pattern is used to solve Combination Sum II?

Combination Sum II is a Combination Sum problem. It belongs to the Backtracking Patterns pattern, in the Combination Sum subpattern.

What is the time complexity of Combination Sum II?

The reference solution runs in O(2^n) time and O(k * n) space.

Which companies ask Combination Sum II?

Combination Sum II has been reported in interviews at Amazon, Uber, Microsoft, ByteDance.

Preparing this workspace.