8 min readRishi

Permutations: Drop the Start Index, Track What You Used

Permutations: Drop the Start Index, Track What You Used

Subsets never walks backwards. After you pick nums[i], the next call starts at i + 1, so [1, 2] appears and [2, 1] does not. That is the right uniqueness rule for sets. Permutations, LeetCode 46, rated Medium, uses the same append-recurse-pop skeleton and throws that rule away. Every order is an answer. The start index is now the bug, not the invariant.

Keep it and you emit the sorted permutation of [1, 2, 3] and nothing else. The interviewer wants to hear why the cursor that de-duplicated Combination Sum and Subsets is illegal here.

What the prompt actually wants

Given distinct integers nums, return every rearrangement. The result has n! lists. Order of those lists does not matter. Order inside a list does.

Input:  nums = [1, 2, 3]
Output: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

An empty input returns [[]] — one permutation of nothing, not an empty result. A single-element input returns [[x]]. Values are unique on this prompt. Repeats are Permutations II, and the skip you need there is not the Subsets II skip. Do not invent it yet.

Combination Sum also has a start index, for the opposite reason: reuse is legal, but [2, 3] and [3, 2] are the same combination. Permutations is the other pole. You cannot pick the same index twice, and order is load-bearing. What you track is membership of indexes, not a cursor that only moves right.

Why in path is the wrong membership test

The first draft a lot of people type looks like this:

def permutations_by_value(nums: list[int]) -> list[list[int]]:
    result: list[list[int]] = []
    path: list[int] = []

    def dfs() -> None:
        if len(path) == len(nums):
            result.append(path.copy())
            return
        for value in nums:
            if value in path:
                continue
            path.append(value)
            dfs()
            path.pop()

    dfs()
    return result

On [1, 2, 3] it happens to work. value in path is O(n) per candidate, so the search is still dominated by the n! output, and uniqueness of values coincides with uniqueness of indexes. The moment the follow-up injects a duplicate, [1, 1, 2], the second 1 is treated as already used the instant the first 1 is on the path. You drop every permutation that needed both. Membership has to be by index, not by value. A boolean array of length n, or an in-place swap that parks chosen indexes in a prefix, is the encoding. in path is a coincidence the unique-input constraint hides.

Copy the path when you record it. The buffer is shared. If you result.append(path), every row aliases one list and they all finish as whatever the last pop left behind — usually []. Same aliasing bug as Subsets and Combination Sum. Scan for .copy() or list(path) before you talk complexity.

Used-array form

Keep a used flags array, a shared path, and recurse until the path is length n. At each depth, try every index that is still free.

def permute(nums: list[int]) -> list[list[int]]:
    """All orderings of distinct nums."""
    n = len(nums)
    result: list[list[int]] = []
    path: list[int] = []
    used = [False] * n

    def dfs() -> None:
        if len(path) == n:
            result.append(path.copy())
            return
        for i in range(n):
            if used[i]:
                continue
            used[i] = True
            path.append(nums[i])
            dfs()
            path.pop()
            used[i] = False

    dfs()
    return result

The loop always restarts at 0. That is the sentence that replaces "I pass i + 1." You skip with used[i], not by moving a cursor. Forget to clear used[i] on the way out and every later sibling thinks that index is gone; you emit only the permutations that pick indexes in increasing order.

The tree for [1, 2, 3]:

  • Path empty. Try index 0 (1).
    • Try 1 (2) → leaf [1, 2, 3]. Pop. Try 2 (3) → leaf [1, 3, 2].
  • Back at empty. Try index 1 (2).
    • Try 0 (1) → leaf [2, 1, 3]. Try 2 (3) → leaf [2, 3, 1].
  • Try index 2 (3). Leaves [3, 1, 2] and [3, 2, 1].

Six leaves. [2, 1, 3] exists because after picking index 1 the loop still considers index 0. Draw this if they hand you a marker: a tree of depth n with n, then n - 1, then n - 2 branches, not the Subsets tree of eight nodes.

Empty nums works because len(path) == n is true on the first call when n is 0, so you record [[]] without entering the loop. A version that assumes n >= 1 and records only inside the loop returns [].

Swap-in-place form

The other honest implementation treats the prefix nums[0:start] as already chosen and the suffix as the remaining pool. At start you try every later index as the next head, swap it into place, recurse start + 1, swap back.

def permute_swap(nums: list[int]) -> list[list[int]]:
    result: list[list[int]] = []
    nums = list(nums)

    def dfs(start: int) -> None:
        if start == len(nums):
            result.append(nums.copy())
            return
        for i in range(start, len(nums)):
            nums[start], nums[i] = nums[i], nums[start]
            dfs(start + 1)
            nums[start], nums[i] = nums[i], nums[start]

    dfs(0)
    return result

start here is a prefix length, not the uniqueness cursor from Subsets. Indexes to the left of start are already in the prefix; you do not swap them into position start a second time. The swap is the used flag. The suffix is the unused set.

This mutates the input. Copy first (nums = list(nums)) if the caller still needs the original order. Recording nums.copy() is required for the same aliasing reason as path.copy(). Empty input works because start == len(nums) is true at start = 0.

Both versions generate the same n! leaves. The used-array version makes "loop from zero, skip taken indexes" obvious, which is what you want if they just watched you solve Subsets. The swap version uses O(1) extra flags. Name both. Implement one. Do not spend the clock proving they are equal.

Complexity, and the thing you cannot beat

  • Time: O(n · n!). There are n! permutations and copying a length-n path at each leaf is O(n). Internal nodes add a constant factor of the same order: at depth k you branch n - k ways. You cannot beat the size of the output.
  • Space: O(n) for the path, the used flags (or the recursion depth in the swap form), plus the result. Do not count the result against the algorithm unless they ask you to.

LeetCode keeps n at most 6, so 6! is 720 and the search finishes. Say n! out loud so they know this is not O(n^2) and not a DP you reconstruct later. Listing every ordering is the output.

Keep the start index and, for [1, 2, 3], you get one leaf: [1, 2, 3]. After you pick 1 the cursor is 1, so 1 can never appear after 2. If they ask "why not pass i + 1," say order, not "it would be slower." Slow is a symptom. Exploring only one order is the cause.

A bitmask does not save you. A mask of remaining indexes is the used array, and you still try every remaining index at each depth. There is no 1 << n loop that lists permutations the way it lists subsets, because a mask does not encode order.

Follow-ups worth having on the whiteboard

Permutations II (LeetCode 47). Values may repeat. Sort first. In the used-array loop, skip a duplicate at the same depth: if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]: continue. The not used[i - 1] is the part people miss. You want the second 1 only when the first 1 is already on the path. If the previous identical value is still free, this node and its left sibling generate the same remaining permutation. Skipping across depths would drop a valid [1, 1, 2]. Same idea as Combination Sum II and Subsets II, different flag because there is no start index to compare against.

In the swap form the skip is uglier: you must not swap two equal values into the same start slot. A small seen set at the current depth, or a scan of nums[start:i], does it. Prefer the used-array version once duplicates are in play; the swap version's "the array is the used set" story fights "do not choose the same value twice at this depth."

Next Permutation (LeetCode 31). One successor in lexicographic order, in place, O(n). Find the rightmost ascent, swap it with the smallest larger suffix value, reverse the suffix. If they pivot here they are done with enumeration. Do not keep DFS-ing.

k-th permutation. At position 0 there are (n - 1)! permutations per remaining candidate; divide k by that factorial, pick, reduce k, repeat. No search tree.

Combinations (LeetCode 77). Put the start index back. [1, 2] and [2, 1] collapse again. Combinations is Subsets with a size cap.

Permutations is Subsets with the uniqueness invariant inverted: you restart the loop at zero, and the thing that prevents reuse is an index flag rather than a cursor. Same append-recurse-pop. Same copy-on-record. The family resemblance is the point of this series — Generate Parentheses, Combination Sum, Subsets, then this. More of that family sits in the Technical Interview category.

Keep reading

Newsletter

New posts, straight to your inbox

One email when a new post goes up. Double opt-in, unsubscribe anytime. Not a daily digest.

Comments

  • No comments yet. Be the first.