Skip to content

How to Fix Permutations Errors

DodaTech Updated 2026-06-26 1 min read

In this tutorial, you'll learn about How to Fix Permutations Errors. We cover key concepts, practical examples, and best practices.

Fix permutations errors when shared list object mutates after adding to result or duplicates not handled.

Quick Fix

Wrong

def perm(n):
    res=[]
    def dfs(cur):
        if len(cur)==len(n): res.append(cur); return
        for x in n:
            if x not in cur: dfs(cur+[x])
    dfs([])
    return res

cur+[x] creates new list each call. Fine for small n. O(n*n!) time.

def perm(n):
    res=[]; used=[False]*len(n)
    def dfs(cur):
        if len(cur)==len(n): res.append(cur.copy()); return
        for i,x in enumerate(n):
            if not used[i]:
                used[i]=True; cur.append(x); dfs(cur); cur.pop(); used[i]=False
    dfs([])
    return res
[1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]. O(n*n!).

Prevention

Track used indices. For each position, try each unused element. Backtrack after.

DodaTech Tools

Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.

FAQ

What is permutations?

All possible orderings of n elements. n! permutations.

Used array?

Track which elements are already placed. Avoids duplicates.

Time?

O(n*n!): n! leaves, O(n) to copy each.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro