Medium interview relevanceRoadmap: Advanced
TimeO(n · n!) to generate all
SpaceO(n) recursion, plus stored output

Why it costs this much

There are n! orderings, and building each one takes O(n).

Code

def permutations(items):
    if not items:
        return [[]]
    return [[x] + p
            for i, x in enumerate(items)
            for p in permutations(items[:i] + items[i+1:])]   # n! results of length n

Common pitfalls

n! grows fast: 10! is about 3.6 million and 15! is over a trillion. Duplicate values in the input need extra handling to avoid repeated results.

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list