Skip to content
mlmentorship

Permutations

Choose unused input positions, restore both path and flags between branches, and distinguish partial orderings from unique repeated-value permutations.

Published · 27 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

Permutations

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

Problem

Input. A list nums of integers. Output. Return a separate list for every permutation of input positions, with each occurrence used once per result. Rules. The reference permutes positions, not distinct values, and leaves nums unchanged. Equal-valued positions remain separate choices, so duplicate value lists may occur. Returned lists must be independent. Result order is not part of the required contract. Empty input returns [[]], one empty ordering. Example. [1, 2] returns [[1, 2], [2, 1]]. For [1, 1], return two independent lists, both [1, 1]; unique-value permutations are a different variant.

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

Fill each path position with every unused index, then pop and clear that same index before the next branch.

Problem trace

Save a copy before unwinding and restoring the live search state

Input and goalReturn every possible ordering of the input values.
Initialize all indices unusedStart choose() with path=[] and used=[F,F,F]. No ordering is complete yet.
[]
Original path and used-index call stack
[]active callF,F,F
inputnums = [1, 2, 3]columnspath | used indicesactioninitializeanswer[]usedByIndex0:F 1:F 2:F
active call
(0, 0)
input
nums = [1, 2, 3]
columns
path | used indices

Recognize it
Use this pattern when every ordering is required and each input position may appear exactly once in each complete path.
Keep true
At every choose call, used[index] is true exactly when that input position has been selected in the current path. Path length is the next output position, and each returned branch restores both structures to their entry state.
Reuse it
Input positions are reusable across sibling branches but forbidden within one path. Mark before recursion and unmark after return. Equal-valued positions remain distinct choices; unique value output requires a separate multiplicity state.
Start choose() with path=[] and used=[F,F,F]. No ordering is complete yet. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does clearing the live path during unwind not erase a saved permutation? Which used flags are restored before the next sibling?
Full interview answer 27 min read

List every ordering of the input positions while preserving each position’s associated value.

Problem

Input. A list nums of integers.

Output. Return a separate list for every permutation of input positions, with each occurrence used once per result.

Rules. The reference permutes positions, not distinct values, and leaves nums unchanged. Equal-valued positions remain separate choices, so duplicate value lists may occur. Returned lists must be independent. Result order is not part of the required contract. Empty input returns [[]], one empty ordering.

Example. [1, 2] returns [[1, 2], [2, 1]]. For [1, 1], return two independent lists, both [1, 1]; unique-value permutations are a different variant.

Picture

For [1,2,3], flags correspond to input indices 0,1,2:

Path at call entryusedMeaning
[][F,F,F]Choose any index
[1][T,F,F]Index zero is unavailable
[1,2][T,T,F]Only index two remains
[1,2,3][T,T,T]Copy one complete ordering
[1,3][T,F,T]Index one was restored and can follow three

Emit 123,132,213,231,312,321 in this source’s DFS order. A compact tree label 123 means [1,2,3], not the integer 123.

Unlike subsets, there is no increasing start boundary. Any unused index can follow a later index, allowing [2,1].

At every recursive entry, true flags identify exactly the positions already selected, and path length identifies the next output slot. Pair mark/append with pop/unmark, including after saving a complete path. A returned branch restores its entry state before its sibling runs.

Save a copy only when path length reaches input length. Later pops must not erase an earlier answer. After the outer call returns, path is empty and all flags are false.

Problem trace

Save a copy before unwinding and restoring the live search state

Worked example: unused positions remain available regardless of their original orderAfter choosing values (1,3) from (1,2,3), value 2 is still unused. An increasing-start rule would wrongly exclude that valid permutation.Used positions are blocked; unusedearlier positions are not1index 02index 13index 2Partial permutation chose values one,then three132Next value two is legal: its sourceposition is still unused.
Read it this way: After choosing values (1,3) from (1,2,3), value 2 is still unused. An increasing-start rule would wrongly exclude that valid permutation. Is unused position one blocked just because its source index precedes the last chosen index two?
Reference drawing

Problem trace

Save a copy before unwinding and restoring the live search state

Worked example: unused positions remain available regardless of their original orderAfter choosing values (1,3) from (1,2,3), value 2 is still unused. An increasing-start rule would wrongly exclude that valid permutation.Used positions are blocked; unusedearlier positions are not1index 02index 13index 2Partial permutation chose values one,then three132Next value two is legal: its sourceposition is still unused.
Execution trace
Input and goalReturn every possible ordering of the input values.
Initialize all indices unusedStart choose() with path=[] and used=[F,F,F]. No ordering is complete yet.
[]
Original path and used-index call stack
[]active callF,F,F
inputnums = [1, 2, 3]columnspath | used indicesactioninitializeanswer[]usedByIndex0:F 1:F 2:F
active call
(0, 0)
input
nums = [1, 2, 3]
columns
path | used indices

Recognize it
Use this pattern when every ordering is required and each input position may appear exactly once in each complete path.
Keep true
At every choose call, used[index] is true exactly when that input position has been selected in the current path. Path length is the next output position, and each returned branch restores both structures to their entry state.
Reuse it
Input positions are reusable across sibling branches but forbidden within one path. Mark before recursion and unmark after return. Equal-valued positions remain distinct choices; unique value output requires a separate multiplicity state.
Start choose() with path=[] and used=[F,F,F]. No ordering is complete yet. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does clearing the live path during unwind not erase a saved permutation? Which used flags are restored before the next sibling?
Read it this way: After choosing values (1,3) from (1,2,3), value 2 is still unused. An increasing-start rule would wrongly exclude that valid permutation. Is unused position one blocked just because its source index precedes the last chosen index two?

Code

def permutations(nums: list[int]) -> list[list[int]]:
   answer: list[list[int]] = []
   path: list[int] = []
   used = [False] * len(nums)

   def choose() -> None:
      if len(path) == len(nums):
         answer.append(path.copy())
         return

      for index, num in enumerate(nums):
         if not used[index]:
            used[index] = True
            path.append(num)
            choose()
            path.pop()
            used[index] = False

   choose()
   return answer

Cost: time and working space.

Working space excludes output: storing lists of length takes slots, including repeated value lists.

Change Length or Value Identity

Start from permutations. Keep reversible state while changing when to emit or which choices are distinct.

  1. Return ordered selections of a given length.

    New task: Fill only size slots, without reusing an input position.

    Picture and change: Stop at size, not input length. Keep every unused index eligible.

    Code: Complete replacement; an integer size outside 0..len(nums) returns []:

    def partial_permutations(nums, size):
       answer, path = [], []
       used = [False] * len(nums)
    
       def choose():
          if len(path) == size:
             answer.append(path.copy())
             return
          for index, value in enumerate(nums):
             if not used[index]:
                used[index] = True
                path.append(value)
                choose()
                path.pop()
                used[index] = False
    
       if 0 <= size <= len(nums):
          choose()
       return answer

    Check: [1,2,3], size two gives six ordered pairs, including [2,1], rather than three unordered subsets. Size zero gives [[]].

    Use when: Ordering matters but full input length does not. There are position selections. Flags and path use working slots; copied output is additional.

  2. Return unique value permutations.

    New task: Equal values must not duplicate output, but their full multiplicity must remain available.

    Picture and change: Replace position flags with remaining counts. Each distinct value is one branch; decrement before recursion and restore afterward. Counter keys stay fixed while counts change.

    Code: Complete replacement for integer values:

    from collections import Counter
    
    
    def unique_permutations(nums):
       counts = Counter(nums)
       answer, path = [], []
    
       def choose():
          if len(path) == len(nums):
             answer.append(path.copy())
             return
          for value in counts:
             if counts[value]:
                counts[value] -= 1
                path.append(value)
                choose()
                path.pop()
                counts[value] += 1
    
       choose()
       return answer

    Check: [1,1,2] gives [1,1,2], [1,2,1], [2,1,1]: three unique orderings, using both ones.

    Use when: Numeric value identity defines uniqueness. Output count becomes . Working storage is ; copying each result still takes work and slots, and each internal call scans distinct keys.

Rebuild Eligibility

Why would a subset-style start boundary lose valid permutations?

Answer: It forbids earlier indices after later ones. Used flags forbid only positions already selected in this path.