Generate All Permutations of Array in DSA Python - Time & Space Complexity
When we generate all permutations of an array, we want to know how the time needed grows as the array gets bigger.
We ask: How many steps does it take to list every possible order of the items?
Analyze the time complexity of the following code snippet.
def permute(nums):
result = []
def backtrack(start=0):
if start == len(nums):
result.append(nums[:])
return
for i in range(start, len(nums)):
nums[start], nums[i] = nums[i], nums[start]
backtrack(start + 1)
nums[start], nums[i] = nums[i], nums[start]
backtrack()
return result
This code generates all possible orders (permutations) of the input list by swapping elements and exploring all options.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls that generate permutations by swapping elements.
- How many times: The recursion explores every possible order, which is factorial of the array length (n!).
As the array size grows, the number of permutations grows very fast because each new element multiplies the options.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 6 (3 x 2 x 1) |
| 5 | 120 (5 x 4 x 3 x 2 x 1) |
| 7 | 5040 (7 x 6 x 5 x 4 x 3 x 2 x 1) |
Pattern observation: The operations grow factorially, which means adding one more element multiplies the work by that element's value.
Time Complexity: O(n * n!)
This means the time grows very fast because we generate all possible orders, and each order takes time proportional to the array size to copy.
[X] Wrong: "Generating permutations is just like looping through the array once, so it should be O(n)."
[OK] Correct: Each element can be in many positions, so the total number of orders grows factorially, not linearly.
Understanding this helps you explain why some problems take much longer as input grows, and shows you can reason about complex recursive solutions.
"What if we only wanted permutations of length k from n elements? How would the time complexity change?"
Practice
permutations from Python's itertools module do when given an array as input?Solution
Step 1: Understand the purpose of permutations
The permutations function creates all possible ways to arrange the elements of the input array.Step 2: Compare with other options
Sorting, removing duplicates, or reversing are different operations and not what permutations does.Final Answer:
Generates all possible orderings of the elements in the array -> Option AQuick Check:
Permutations = all orderings [OK]
- Confusing permutations with sorting
- Thinking permutations remove duplicates
- Assuming permutations reverse the array
[1, 2, 3] using itertools.permutations in Python?Solution
Step 1: Check correct import and function name
The correct module is itertools and the function is permutations (plural).Step 2: Verify syntax correctness
import itertools perms = itertools.permutations([1, 2, 3]) correctly imports itertools and calls itertools.permutations with the list.Final Answer:
import itertools perms = itertools.permutations([1, 2, 3]) -> Option CQuick Check:
Correct import and function name = import itertools perms = itertools.permutations([1, 2, 3]) [OK]
- Using singular 'permutation' instead of 'permutations'
- Wrong import statement
- Calling function without module prefix when not imported directly
from itertools import permutations
for p in permutations([1, 2]):
print(p)Solution
Step 1: Understand permutations output type
itertools.permutations returns tuples representing each permutation.Step 2: List all permutations of [1, 2]
They are (1, 2) and (2, 1), printed on separate lines.Final Answer:
(1, 2)\n(2, 1) -> Option AQuick Check:
Permutations of two elements = two tuples [OK]
- Expecting lists instead of tuples
- Repeating same permutation twice
- Confusing output format with string or list
[1, 2, 3]. What is the error?from itertools import permutations perms = permutations([1, 2, 3]) print(perms)
Solution
Step 1: Understand what permutations returns
permutations returns an iterator object, not a list of permutations directly.Step 2: Printing the iterator shows its object info, not permutations
To see permutations, you must iterate or convert to list first.Final Answer:
It prints a permutations object, not the permutations themselves -> Option BQuick Check:
Printing iterator shows object info, not data [OK]
- Expecting print to show permutations directly
- Thinking import is wrong
- Believing input must be tuple
[1, 2, 2] but only keep unique permutations (no duplicates). Which approach correctly achieves this in Python?Solution
Step 1: Understand duplicates in permutations
Input has repeated elements, so permutations include duplicates.Step 2: Remove duplicates by converting permutations to a set
Using set() on permutations removes duplicate tuples, keeping unique permutations only.Final Answer:
Use set(permutations([1, 2, 2])) to remove duplicate tuples -> Option DQuick Check:
Set removes duplicates from permutations [OK]
- Using set on input list before permutations (loses duplicates)
- Assuming sorting removes duplicates
- Not removing duplicates at all
Ready to prove it?
Pass the test and this pattern moves unknown
