Generate all permutations in go
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Generating permutations is a classic combinatorics problem and a common interview topic in Go. The practical challenge is not only correctness, but also writing code that avoids accidental slice mutation and unnecessary allocations. A solid backtracking implementation is usually the best starting point.
What a Permutation Generator Must Guarantee
Given n unique elements, a permutation generator should return exactly n! arrangements, each containing every element once. For input with duplicates, you often need a deduplication strategy to avoid repeated output.
Performance matters quickly. Even at n = 10, the count is 3,628,800 permutations. In real systems, you usually stream results, limit output, or run the algorithm only for small sets.
Backtracking Implementation in Go
This approach builds permutations incrementally. A used array tracks which items are already in the current path.
The critical detail is cloning path before appending to result. Without cloning, all rows can point to the same backing array and final output becomes incorrect.
In Place Swap Variant
An alternative uses swaps inside a single slice. This can reduce extra state and often runs fast in Go.
This version mutates input while searching, then restores it by swapping back. If callers need the input untouched, pass a copy.
Handling Duplicate Values
If input may contain duplicates, sort first and skip repeated choices at the same depth.
The duplicate skip rule depends on sorted order and previous index usage state.
Practical Usage Guidance
In production, avoid materializing huge permutation sets in memory. Prefer a callback style generator so each permutation can be consumed immediately.
Returning false from visit allows early stop when you only need a subset.
Common Pitfalls
- Appending the same
pathslice to results without cloning, which corrupts output. - Forgetting to restore state during backtracking, such as not resetting
usedor not swapping back. - Generating duplicates for repeated input values because skip logic is missing.
- Allocating very large result slices for high
n, causing memory spikes. - Ignoring factorial growth and trying to generate full permutations for large inputs in request path code.
Summary
- Backtracking with
usedflags is clear, correct, and easy to maintain. - In place swap generation is compact and efficient when mutation is acceptable.
- Duplicate handling needs sorted input and depth aware skip rules.
- Clone slices before storing results to avoid shared backing array bugs.
- Prefer streaming or early stop patterns for realistic workloads.
Related reading
- Generate all permutations of a list without adjacent equal elements
- Generate all strings under length N in C
- generate all subsets of size k from a set
- Generate all unique substrings for given string
- Generate an integer that is not among four billion given ones
- Generate cartesian product in decreasing sum order
- Generate large prime number with specified last digits
- Generate N random numbers within a range with a constant sum

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.