Permutations Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Permutations runs in O(n!) time and O(n) space, in C# as in every other language.
- ✓System.Linq has no Permutations() operator, Enumerable ships Select, Where, OrderBy and dozens more, but never permutation generation, so like Go and Java this is hand-rolled.
- ✓Swap with tuple deconstruction, (list[i], list[j]) = (list[j], list[i]);, valid C# 7+ syntax that swaps without a temporary variable and is what a modern C# reviewer expects over the three-line temp-variable swap older codebases still have scattered through them.
- ✓The C# trap: yield return currentArray inside a swap-based recursive iterator hands the CALLER a reference to the exact array the iterator keeps mutating on every subsequent swap, C#'s deferred iterator execution means the consumer's foreach body runs interleaved with the generator's own mutation, so unless you yield return (T[])currentArray.Clone(), materializing the sequence with .ToList() produces a list where every entry is the SAME array reference, all showing whatever the final permutation happened to be.
- ✓n! is n!, and the tuple-deconstruction swap compiles to the same three-move-with-temp IL a hand-written swap would, no overhead from the syntax sugar.
What Permutations actually is
Permutations in C#: what you actually reach for
C# implementation
using System.Collections.Generic;
public static class Permutations
{
public static IEnumerable<T[]> Of<T>(T[] items)
{
var array = (T[])items.Clone();
foreach (var perm in Recurse(array, 0))
{
yield return perm;
}
}
private static IEnumerable<T[]> Recurse<T>(T[] array, int k)
{
if (k == array.Length)
{
yield return (T[])array.Clone(); // without Clone(), every yield aliases `array`
yield break;
}
for (int i = k; i < array.Length; i++)
{
(array[k], array[i]) = (array[i], array[k]); // tuple-deconstruction swap
foreach (var perm in Recurse(array, k + 1))
{
yield return perm;
}
(array[k], array[i]) = (array[i], array[k]); // undo
}
}
}
// var first5 = Permutations.Of(new[] { 1, 2, 3, 4 }).Take(5); // only 5 leaves computedThink Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(n!)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Permutations?
System.Linq has no Permutations() operator, Enumerable ships Select, Where, OrderBy and dozens more, but never permutation generation, so like Go and Java this is hand-rolled. There is no single dominant NuGet package for it the way itertools is dominant in Python, which is itself informative about how rarely production C# code needs full permutation enumeration outside interview problems and combinatorial test-data generators.
What is the most common C# mistake when implementing Permutations?
yield return currentArray inside a swap-based recursive iterator hands the CALLER a reference to the exact array the iterator keeps mutating on every subsequent swap, C#'s deferred iterator execution means the consumer's foreach body runs interleaved with the generator's own mutation, so unless you yield return (T[])currentArray.Clone(), materializing the sequence with .ToList() produces a list where every entry is the SAME array reference, all showing whatever the final permutation happened to be. This is the C#-specific flavor of the aliasing bug every language here has some version of, sharper because yield return makes the mutation-during-enumeration look deliberate rather than an obvious accident.
How does Permutations actually perform in C#?
n! is n!, and the tuple-deconstruction swap compiles to the same three-move-with-temp IL a hand-written swap would, no overhead from the syntax sugar. The yield return generator form defers all work until enumerated, so Permutations(items).Take(5) genuinely only computes 5 leaves' worth of recursion and swaps, not all n!, which an eager List<T[]>-returning version cannot do no matter how the caller uses the result afterward. Time complexity is O(n!) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for GitHub Copilot, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.