Skip to content
mlmentorship

Save each increasing-index choice path, then undo the last choice

Copy each answer before extending a shared path, then change output length or duplicate-value policy.

Published · 12 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Save each increasing-index choice path, then undo the last choice

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A list nums of distinct integers. Output. Return one list for each subset, including the empty subset and the subset containing every value. Rules. A value may be selected at most once per subset; changing selection order does not create a new subset. Leave the input unchanged. Each returned list must be independent of the others. Output order is not required. Empty input returns [[]]; duplicate values require the separate policy below. Example. [1, 2, 3] has eight subsets: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]. The selections [1, 2] and [2, 1] are the same subset, not two answers.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Save every current path, then recurse only to larger indices and pop the chosen value on return.

Problem trace

Increasing choice indices generate each subset once, including the empty subset

Input and goalReturn every subset of the input values.
Save the empty pathchoose(0) first copies [] into answer; indices 0, 1, and 2 remain available.
[]active callstart 0
inputnums = [1, 2, 3]columnspath | startactionsave []answer[[]]
active call
(0, 0)
input
nums = [1, 2, 3]
columns
path | start

Recognize it
Use this pattern when every combination of distinct input positions is valid and order does not matter, so each partial selection must be emitted once.
Keep true
On entry to choose(start), path contains indices in strictly increasing order, answer already contains every path visited earlier in DFS order, and only indices start or greater may extend this path.
Reuse it
When order should not create duplicates, advance a start boundary after each choice; this same skeleton generates combinations, k-subsets, and increasing-index selections.
choose(0) first copies [] into answer; indices 0, 1, and 2 remain available. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is [1,2] saved once while [2,1] is never generated? Where is the empty subset saved?
Full interview answer 12 min read

List every subset of a collection of distinct values, including choosing no values at all.

Problem

Input. A list nums of distinct integers.

Output. Return one list for each subset, including the empty subset and the subset containing every value.

Rules. A value may be selected at most once per subset; changing selection order does not create a new subset. Leave the input unchanged. Each returned list must be independent of the others. Output order is not required. Empty input returns [[]]; duplicate values require the separate policy below.

Example. [1, 2, 3] has eight subsets: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]. The selections [1, 2] and [2, 1] are the same subset, not two answers.

Picture

Each node is a saved path; each edge chooses one input index. Indices increase along every root-to-node route, so an unordered selection has only one construction order.

Increasing indices choose membership without emitting every ordering

Increasing choice indices erase duplicate orderingsIndices 0 then 1 generate subset (1,2). Attempting 1 then 0 goes backward and would duplicate the same membership.A permitted choice order emits eachmembership once01Allowed order: emit this membership.10Backward order: duplicate membership;do not emit.
Read it this way: Indices 0 then 1 generate subset (1,2). Attempting 1 then 0 goes backward and would duplicate the same membership. Why is the backward one-then-zero path a duplicate rather than a new subset?
Reference drawing

Increasing indices choose membership without emitting every ordering

Increasing choice indices erase duplicate orderingsIndices 0 then 1 generate subset (1,2). Attempting 1 then 0 goes backward and would duplicate the same membership.A permitted choice order emits eachmembership once01Allowed order: emit this membership.10Backward order: duplicate membership;do not emit.
Derivation
Increasing indices choose membership without emitting every orderingAll eight subsets of one-two-three appear once in the increasing-index tree. A proposed two-one branch is rejected because it returns to an earlier index. This excludes duplicate orderings without excluding the valid subset one-two.[][1][2][3][1,2][1,3][2,3][1,2,3][2,1] REJECTEDindex would gobackwardIncreasing indices emit each subset once, notevery order.
Each extension uses a later index. The rejected [2,1] ordering represents membership already emitted as [1,2]. All eight distinct subsets remain.
Read it this way: Indices 0 then 1 generate subset (1,2). Attempting 1 then 0 goes backward and would duplicate the same membership. Why is the backward one-then-zero path a duplicate rather than a new subset?

Read it this way: save a copy at every node. Return along an edge by undoing its choice before trying a sibling.

At choose(start), the path contains only earlier, strictly increasing positions. This call may extend it using any index from start onward. It owns each append that it later removes.

Reference drawing

Problem trace

Increasing choice indices generate each subset once, including the empty subset

Worked example: each position supplies one independent include-or-exclude choiceFor values (1,2), four binary choice paths produce four distinct subsets. Excluding a value is a branch, not an omitted decision.Every include-or-exclude decisionpath emits one membershiptake 1?take 2?result--{}-✓{2}✓-{1}✓✓{1,2}Two explicit exclusions emit theempty subset.
Execution trace
Input and goalReturn every subset of the input values.
Save the empty pathchoose(0) first copies [] into answer; indices 0, 1, and 2 remain available.
[]active callstart 0
inputnums = [1, 2, 3]columnspath | startactionsave []answer[[]]
active call
(0, 0)
input
nums = [1, 2, 3]
columns
path | start

Recognize it
Use this pattern when every combination of distinct input positions is valid and order does not matter, so each partial selection must be emitted once.
Keep true
On entry to choose(start), path contains indices in strictly increasing order, answer already contains every path visited earlier in DFS order, and only indices start or greater may extend this path.
Reuse it
When order should not create duplicates, advance a start boundary after each choice; this same skeleton generates combinations, k-subsets, and increasing-index selections.
choose(0) first copies [] into answer; indices 0, 1, and 2 remain available. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is [1,2] saved once while [2,1] is never generated? Where is the empty subset saved?
Read it this way: For values (1,2), four binary choice paths produce four distinct subsets. Excluding a value is a branch, not an omitted decision. Which two decisions produce the empty subset rather than skipping the decision process?

Save path.copy(), not path itself. All recursion levels share the active mutable list, but saved answers must not share that list.

Code

def subsets(nums: list[int]) -> list[list[int]]:
   answer: list[list[int]] = []
   path: list[int] = []

   def choose(start: int) -> None:
      answer.append(path.copy())
      for index in range(start, len(nums)):
         path.append(nums[index])
         choose(index + 1)
         path.pop()

   choose(0)
   return answer

There are position subsets. Materializing their copied lists takes time and output space. The active path and recursive stack separately use working space. Python’s recursion limit still applies. Empty input returns [[]], not [].

Failure Check

Saving path directly makes all answers track the same later mutations. Forgetting pop leaves a sibling with the previous branch’s state. Keeping the same start permits reuse instead of selecting each position at most once. On [1,1], the original emits two separate [1] answers; it has not promised duplicate-value suppression.

Change the Answer Length

New task: Return only selections of a fixed integer length.

Picture and change: Save only complete requested lengths. Stop after saving; prune when too few positions remain. Increasing indices still prevent alternative orderings of one selection.

def k_subsets(nums, size):
   answer, path = [], []
   def choose(start):
      if len(path) == size:
         answer.append(path.copy())
         return
      if len(nums) - start < size - len(path):
         return
      for index in range(start, len(nums)):
         path.append(nums[index])
         choose(index + 1)
         path.pop()
   if size >= 0:
      choose(0)
   return answer

Check: [1,2,3], size 2, returns [[1,2],[1,3],[2,3]]. Size zero returns [[]]; negative or excessive sizes return [].

Use when: The output-length requirement changes.

Change the Duplicate Policy

New task: Equal input values must not duplicate returned value subsets.

Picture and change: Sort a copy and skip equal choices among siblings only. A deeper equal position remains available, so [2,2] is still possible.

def unique_subsets(nums):
   choices = sorted(nums)
   answer, path = [], []
   def choose(start):
      answer.append(path.copy())
      for index in range(start, len(choices)):
         if index > start and choices[index] == choices[index - 1]:
            continue
         path.append(choices[index])
         choose(index + 1)
         path.pop()
   choose(0)
   return answer

Check: [1,2,2] returns [[],[1],[1,2],[1,2,2],[2],[2,2]] without changing the input. Sorting adds work and storage before output enumeration. Output can still be exponential; fewer duplicates are not a polynomial bound.

Use when: Unique value multisets replace distinct-position selections.

Transfer Check

Why skip duplicate siblings but not every duplicate value?

Answer

Equal sibling choices lead to the same value continuation. Deeper equal positions represent legitimate multiplicity, such as [2,2]. The skip must depend on the current start boundary.