Problems/Backtracking/Find All Permutations
Backtracking
medium

Find All Permutations

Generate all possible orderings of elements in a list. This problem tests your ability to think recursively and use backtracking effectively, common skills in algorithm design.

recursionbacktrackingpermutationcombinatoricslist

Problem Statement

Given a list of distinct elements, write a function that returns a list of all possible permutations of those elements. The order of the permutations in the output does not matter.

Example 1
Input: [1, 2, 3]
Output: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
These are all the possible ways to arrange the numbers 1, 2, and 3.
Example 2
Input: [7, 8]
Output: [[7, 8], [8, 7]]
These are all the possible ways to arrange the numbers 7 and 8.
Constraints
  • -The input list will contain only distinct elements.
  • -The input list will contain at least one element.
  • -The elements in the input list can be of any data type.
  • -The order of permutations in the output is not important.
  • -The length of the input list will not exceed 10.

Brute Force Approach

Imagine you're trying to arrange books on a shelf. The brute-force approach would be to try every single possible arrangement and list them all out. This involves generating all possible sequences, which becomes very inefficient as the number of elements grows, as you're repeatedly calculating the same combinations.

TimeO(n! * n)
SpaceO(n!)

Ready to practice?

Work through this problem with AI coaching and get real-time feedback

Practice This Problem