Tutorialspoint
Problem
Solution
Submissions

Permutations

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C program to generate all possible permutations of a given array of distinct integers. A permutation is a rearrangement of the elements of the array where each element appears exactly once. The order of the permutations in the output doesn't matter.

Example 1
  • Input: nums = [1,2,3]
  • Output: [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
  • Explanation:
    • For the array [1,2,3], we need to generate all possible arrangements.
    • There are 3! = 6 possible permutations.
    • We use backtracking to systematically generate each permutation.
Example 2
  • Input: nums = [0,1]
  • Output: [[0,1], [1,0]]
  • Explanation:
    • For the array [0,1], we need to generate all possible arrangements.
    • There are 2! = 2 possible permutations.
    • The permutations are [0,1] and [1,0].
Constraints
  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • All the integers of nums are unique
  • Time Complexity: O(n * n!), where n is the length of the array
  • Space Complexity: O(n * n!) for storing all permutations
ArraysTech MahindraApple
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use backtracking to systematically generate all permutations
  • For each position in the permutation, try placing each unused number
  • Keep track of which numbers have been used in the current permutation
  • When you've placed all numbers, you've found a complete permutation
  • Use recursion to build permutations element by element
  • You can use a boolean array or set to track which elements have been used
  • You can also swap elements in the array to generate permutations without extra space

Steps to solve by this approach:

 Step 1: Create a backtracking function that builds permutations one element at a time.
 Step 2: Use an array or bit mask to keep track of which elements have been used in the current permutation.
 Step 3: For each position in the permutation, try placing each unused number.
 Step 4: After placing a number, mark it as used before moving to the next position.
 Step 5: When we've filled all positions, we've found a complete permutation.
 Step 6: After adding a permutation to our result, backtrack by marking the last placed number as unused.
 Step 7: Continue this process until all possible permutations have been generated.

Submitted Code :