Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Permutations Implementation in C#

14 min readintermediate
Website QA and SEO audits

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

Generating all permutations of a collection means producing every possible ordering of its elements, n! orderings for n distinct elements, which is why the time bound is O(n!) regardless of how cleverly you generate them: that many results exist, full stop. The real question is generation STRATEGY, not output size: swap two elements in place and recurse (Heap's-algorithm-style backtracking), or walk a state that already IS a permutation and mutate it into the next one. The eight languages below split cleanly on ecosystem support: some ship a permutations iterator you call directly, some ship nothing and force you to hand-write the backtracking, and TypeScript's type system alone can compute every permutation of a literal union as a compile-time-only operation with no runtime code at all, a capability none of the other seven touch. Auxiliary space stays O(n): the recursion depth plus the array being permuted in place, independent of how many of the n! results you keep.

Permutations in C#: what you actually reach for

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.

C# implementation

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. Return IEnumerable<T[]> and yield return each permutation from the recursive generator so a caller who only needs the first few can stop early via .Take(k) without materializing the rest.
csharp
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 computed

Think 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 Free

The C#-specific 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. 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.

Performance in C#, beyond the O(n!)

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. The asymptotic cost is the same in every language, O(n!) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Permutations between languages.

Real-World Applications

Permutations applies wherever its problem shape appears in your own code. In C#, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Permutations helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Permutations appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Permutations over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Permutations to build pattern recognition. In C#, demonstrate proficiency with LINQ and async patterns to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic C# code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Before paying for GitHub Copilot, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.