Good afternoon! 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:
1str := "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
​
package main
​
import (
"fmt"
"reflect"
)
​
func permutations(str string) []string {
// fill in this function
return []string{}
}
​
func main() {
str := "cat"
fmt.Println(permutations(str))
​
// test cases start
fmt.Printf("============================================================\n")
passed := true
if reflect.DeepEqual(permutations("abc"), []string{"cba", "bca", "bac", "cab", "acb", "abc"}) == true {
fmt.Println("TEST 1 --- PASSED")
} else {
fmt.Println("TEST 1 --- FAILED : got ", permutations("abc"), " expected ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']")
passed = false
}
if reflect.DeepEqual(permutations("a"), []string{"a"}) == true {
fmt.Println("TEST 2 --- PASSED")
} else {
fmt.Println("TEST 2 --- FAILED : got ", permutations("a"), " expected ['a']")
Tired of reading? Watch this video explanation!
To change the speed of the video or see it in full screen, click the icons to the right of the progress bar.

We'll now take you through what you need to know.
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.