Good evening! Here's our prompt for today.
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:
1String str = "abc";
2permutations(str);
3// abc
4// acb
5// bac
6// bca
7// cba
8// 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!)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
​
import static org.junit.Assert.*;
​
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.List;
import org.junit.*;
import org.junit.runner.*;
import org.junit.runner.notification.*;
​
public class MainTest {
​
public static String[] permutations(String str) {
// fill in this method
return "";
}
​
// tests
​
public void firstTest() {
assertEquals(
this.permutations("abc"),
new String[] { "abc", "acb", "bac", "bca", "cab", "cba" }
);
}
​
public void secondTest() {
assertEquals(this.permutations("a"), new String[] { "a" });
Here's a video of us explaining the solution.
To change the speed of the video or see it in full screen, click the icons to the right of the progress bar.

Here's how we would solve this problem...
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.