Skip to content
Hello Python

Checking your account…

Sign in to save your code and progress across devices. The lesson and problem statement remain public.

Loading the interactive Interview workspace.If it does not appear, the problem and learning material remain readable, but browser execution is unavailable.Reload Interview workspace

Problem

Implement Solution.subsets(nums). nums contains distinct integers. Return the complete power set, including the empty subset. Subset and value order do not matter.

Starter code

class Solution:
    def subsets(self, nums):
        pass
Test cases

three-values

{
  "args": [
    [
      1,
      2,
      3
    ]
  ]
}

Expected: [[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]

Wizard outline
  1. Step 1: Initialize Solution.subsets

    Replace the empty starter with the first real state owned by Solution.subsets. A small, named state is easier to verify than a complete algorithm. Establish it before adding the branch or loop that changes it.

  2. Step 2: Pass the Empty Choice Tree case

    Complete the readable core algorithm for one representative Interview case. Record every recursion node as a valid subset and extend only with later values.

  3. Step 3: Harden the Three Values boundary

    Repair the reviewed boundary and pass the complete submission contract. Every subset has a unique increasing sequence of input indices; the recursion visits that sequence once and records its path, including the empty sequence at the root.

Footguns and prerequisites
  • The empty subset is part of every power set and must be recorded before choosing anything.
  • recursion and backtracking
Reviewed references
Practice prerequisites
  • Complete One Backtracking Frame(opens in a new tab)

    Complete One Backtracking Frame isolates before expanding each choice, path equals the original caller-owned prefix; every emitted candidate contains exactly one additional element. That focused state discipline is required when implementing subsets as a complete Interview Problem.

Recommended approach and implementation

Append a copy of the current path at every recursion node, then extend it with each value from a monotone start index.

Why it works: Every subset has a unique increasing sequence of input indices; the recursion visits that sequence once and records its path, including the empty sequence at the root.

class Solution:
    def subsets(self, nums):
        """
        Checkpoint 1: initialize the state owned by this Interview contract.
        Checkpoint 2: assemble the primary transition without hiding the boundary.
        """
        result = []
        path = []
        def backtrack(start):
            result.append(path[:])
            for index in range(start, len(nums)):
                path.append(nums[index])
                backtrack(index + 1)
                path.pop()
        backtrack(0)
        return result
Similar exercises