Tutorialspoint
Problem
Solution
Submissions

Generate All Permutations of a String.

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 15

Write a Python program that generates all possible permutations of a given string.

Example 1
  • Input: "abc"
  • Output: ["abc", "acb", "bac", "bca", "cab", "cba"]
  • Explanation:
    • Step 1: Take the input string "abc".
    • Step 2: Generate all possible permutations of the string.
    • Step 3: Return the list of permutations as the result.
Example 2
  • Input: "xy"
  • Output: ["xy", "yx"]
  • Explanation:
    • Step 1: Take the input string "xy".
    • Step 2: Generate all possible permutations of the string.
    • Step 3: Return the list of permutations as the result.
Constraints
  • 1 ≤ len(string) ≤ 6
  • The string consists of unique lowercase English letters.
  • Time Complexity: O(n!), where n is the length of the string.
  • Space Complexity: O(n!)
NumberRecursionWiproKPMG
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 recursion to generate permutations.
  • Swap characters to generate different permutations.
  • Handle edge cases where the string length is 1 or 0.

Steps to solve by this approach:

 Step 1: Use a backtracking approach with a recursive helper function.
 Step 2: If no characters remain, add the current path to the result.
 Step 3: For each character in the remaining set, choose it and add to the current path.
 Step 4: Recursively generate permutations with the chosen character removed from remaining characters.
 Step 5: Collect all permutations in the result array and return it.

Submitted Code :