
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.
- Starting with "abc", we can place 'a' in first position and permute "bc" to get "abc", "acb".
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.
- With string "ab", we can place 'a' first and get "ab".
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
Editorial
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. |
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