Generate All String Permutations
Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.
Description
Write an algorithm that takes an input string like "abc", and prints out all possible permutations of the string. A permutation of a group of elements is defined as one of the n! number possible arrangements the elements can take, where n is the number of elements in the range.
We'd expect the following to hold true, note the permutations printed out:
const str = "abc"
permutations(str)
// abc
// acb
// bac
// bca
// cba
// cab
String str = "abc";
permutations(str);
// abc
// acb
// bac
// bca
// cba
// cab
str = "abc"
permutations(str)
# abc
# acb
# bac
# bca
# cba
# cab
std::string str = "abc";
permutations(str);
// abc
// acb
// bac
// bca
// cba
// cab
string str = "abc";
Permutations(str);
// abc
// acb
// bac
// bca
// cba
// cab
str := "abc"
permutations(str)
// abc
// acb
// bac
// bca
// cba
// cab
A hint here: break the problem down, and think about what steps are going to be repeated. How would we get from "abc" to "acb"?
Constraints
- The string will only consist of lowercase letters
- Length of the string <=
7 - Expected time complexity :
O(n*n!) - Expected space complexity :
O(n*n!)
```js
function permutations(str) {
// Fill in this method
return str;
}
console.log(permutations("abc"));
```
```java
public class Main {
public static String permutations(String str) {
// Fill in this method
return str;
}
public static void main(String[] args) {
System.out.println(permutations("abc"));
}
}
```
```python
def permutations(str):
# Fill in this method
return str
print(permutations("abc"))
```
```cpp
#include <iostream>
#include <string>
std::string permutations(std::string str) {
// Fill in this method
return str;
}
int main() {
std::cout << permutations("abc");
return 0;
}
```
```csharp
class Program
{
public static string Permutations(string str)
{
// Fill in this method
return str;
}
static void Main(string[] args)
{
Console.WriteLine(Permutations("abc"));
}
}
```
```go
package main
import "fmt"
func permutations(str string) string {
// Fill in this method
return str
}
func main() {
fmt.Println(permutations("abc"))
}
```
CONTINUE WITH ALGODAILY PREMIUM
Keep going with the complete tutorial.
Unlock the remaining explanations and exercises, alongside the full learning library.
Explore Premium →