Bird
Raised Fist0
DSA Pythonprogramming~5 mins

Generate All Permutations of Array in DSA Python - Time & Space Complexity

Choose your learning style10 modes available
Time Complexity: Generate All Permutations of Array
O(n * n!)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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!).
How Execution Grows With Input

As the array size grows, the number of permutations grows very fast because each new element multiplies the options.

Input Size (n)Approx. Operations
36 (3 x 2 x 1)
5120 (5 x 4 x 3 x 2 x 1)
75040 (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.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding this helps you explain why some problems take much longer as input grows, and shows you can reason about complex recursive solutions.

Self-Check

"What if we only wanted permutations of length k from n elements? How would the time complexity change?"

Practice

(1/5)
1. What does the function permutations from Python's itertools module do when given an array as input?
easy
A. Generates all possible orderings of the elements in the array
B. Sorts the array in ascending order
C. Removes duplicate elements from the array
D. Returns the array reversed

Solution

  1. Step 1: Understand the purpose of permutations

    The permutations function creates all possible ways to arrange the elements of the input array.
  2. Step 2: Compare with other options

    Sorting, removing duplicates, or reversing are different operations and not what permutations does.
  3. Final Answer:

    Generates all possible orderings of the elements in the array -> Option A
  4. Quick Check:

    Permutations = all orderings [OK]
Hint: Permutations = all ways to arrange elements [OK]
Common Mistakes:
  • Confusing permutations with sorting
  • Thinking permutations remove duplicates
  • Assuming permutations reverse the array
2. Which of the following is the correct syntax to generate all permutations of the list [1, 2, 3] using itertools.permutations in Python?
easy
A. from itertools import permutation perms = permutations([1, 2, 3])
B. from itertools import permutation perms = permutation([1, 2, 3])
C. import itertools perms = itertools.permutations([1, 2, 3])
D. import itertools perms = itertools.permutation([1, 2, 3])

Solution

  1. Step 1: Check correct import and function name

    The correct module is itertools and the function is permutations (plural).
  2. Step 2: Verify syntax correctness

    import itertools perms = itertools.permutations([1, 2, 3]) correctly imports itertools and calls itertools.permutations with the list.
  3. Final Answer:

    import itertools perms = itertools.permutations([1, 2, 3]) -> Option C
  4. Quick Check:

    Correct import and function name = import itertools perms = itertools.permutations([1, 2, 3]) [OK]
Hint: Use plural 'permutations' and correct import [OK]
Common Mistakes:
  • Using singular 'permutation' instead of 'permutations'
  • Wrong import statement
  • Calling function without module prefix when not imported directly
3. What is the output of the following code?
from itertools import permutations
for p in permutations([1, 2]):
    print(p)
medium
A. (1, 2)\n(2, 1)
B. [1, 2]\n[2, 1]
C. (1, 2)\n(1, 2)
D. [1, 2]\n[1, 2]

Solution

  1. Step 1: Understand permutations output type

    itertools.permutations returns tuples representing each permutation.
  2. Step 2: List all permutations of [1, 2]

    They are (1, 2) and (2, 1), printed on separate lines.
  3. Final Answer:

    (1, 2)\n(2, 1) -> Option A
  4. Quick Check:

    Permutations of two elements = two tuples [OK]
Hint: Permutations output tuples, not lists [OK]
Common Mistakes:
  • Expecting lists instead of tuples
  • Repeating same permutation twice
  • Confusing output format with string or list
4. The following code is intended to print all permutations of [1, 2, 3]. What is the error?
from itertools import permutations
perms = permutations([1, 2, 3])
print(perms)
medium
A. The import statement is incorrect
B. It prints a permutations object, not the permutations themselves
C. The list should be converted to a tuple first
D. The function permutations does not exist

Solution

  1. Step 1: Understand what permutations returns

    permutations returns an iterator object, not a list of permutations directly.
  2. Step 2: Printing the iterator shows its object info, not permutations

    To see permutations, you must iterate or convert to list first.
  3. Final Answer:

    It prints a permutations object, not the permutations themselves -> Option B
  4. Quick Check:

    Printing iterator shows object info, not data [OK]
Hint: Convert iterator to list to see permutations [OK]
Common Mistakes:
  • Expecting print to show permutations directly
  • Thinking import is wrong
  • Believing input must be tuple
5. You want to generate all permutations of the array [1, 2, 2] but only keep unique permutations (no duplicates). Which approach correctly achieves this in Python?
hard
A. Use list(permutations([1, 2, 2])) directly
B. Use permutations(set([1, 2, 2])) to generate permutations of unique elements
C. Sort the array first, then use permutations
D. Use set(permutations([1, 2, 2])) to remove duplicate tuples

Solution

  1. Step 1: Understand duplicates in permutations

    Input has repeated elements, so permutations include duplicates.
  2. Step 2: Remove duplicates by converting permutations to a set

    Using set() on permutations removes duplicate tuples, keeping unique permutations only.
  3. Final Answer:

    Use set(permutations([1, 2, 2])) to remove duplicate tuples -> Option D
  4. Quick Check:

    Set removes duplicates from permutations [OK]
Hint: Convert permutations to set to remove duplicates [OK]
Common Mistakes:
  • Using set on input list before permutations (loses duplicates)
  • Assuming sorting removes duplicates
  • Not removing duplicates at all
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard