Tutorialspoint
Problem
Solution
Submissions

All Permutations of a String

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

Write a JavaScript program to generate all possible permutations of a given string. A permutation is a rearrangement of the characters in the string. The function should return an array containing all unique permutations of the input string.

Example 1
  • Input: str = "abc"
  • Output: ["abc", "acb", "bac", "bca", "cab", "cba"]
  • Explanation:
    • Starting with "abc", we can place 'a' in first position and permute "bc" to get "abc", "acb".
    • Placing 'b' in first position and permuting "ac" gives us "bac", "bca".
    • Placing 'c' in first position and permuting "ab" gives us "cab", "cba".
    • All 6 permutations are generated using recursive backtracking.
Example 2
  • Input: str = "ab"
  • Output: ["ab", "ba"]
  • Explanation:
    • With string "ab", we can place 'a' first and get "ab".
    • We can place 'b' first and get "ba".
    • Total of 2 permutations are possible for a 2-character string.
Constraints
  • 1 ≤ str.length ≤ 8
  • str consists of unique lowercase English letters
  • Time Complexity: O(n! * n) where n is length of string
  • Space Complexity: O(n! * n) for storing all permutations
  • The order of permutations in output array doesn't matter
RecursionBacktracking DropboxD. E. Shaw
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 recursive backtracking to generate permutations
  • For each position, try placing each remaining character
  • Make a choice, recurse, then backtrack by undoing the choice
  • Use a visited array or string manipulation to track used characters
  • When the current permutation length equals string length, add to result
  • Consider using array swapping for efficient character placement

Steps to solve by this approach:

 Step 1: Create a result array to store all permutations and convert string to character array.

 Step 2: Define a recursive backtracking function that takes current permutation and remaining characters.
 Step 3: Set base case - when no characters remain, add current permutation to result.
 Step 4: For each remaining character, add it to current permutation (choose step).
 Step 5: Create new remaining array without the chosen character and recurse.
 Step 6: Remove the last added character from current permutation (backtrack step).
 Step 7: Return the result array containing all permutations.

Submitted Code :