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

Permutations Implementation in TypeScript

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 TypeScript as in every other language.
  • ✓Runtime: nothing, same gap as JavaScript. Type-level: TypeScript's recursive conditional types can compute every permutation of a literal union entirely at compile time, something no other language here does purely in its type system, `type Permutation<T, K = T> = [T] extends [never] ?
  • ✓Type the runtime swap-based function's return as T[][], not any[][], generics carry through cleanly since the function never inspects T's shape, only moves it around, so `function permutations<T>(items: T[]): T[][]` costs nothing and gives every caller full inference.
  • ✓The TypeScript trap: The compile-time Permutation<T> type is a recursive conditional type, and tsc has a real recursion-depth ceiling: in practice, past roughly single-digit union sizes (9 members is already 362,880 tuple types) you hit 'Type instantiation is excessively deep and possibly infinite,' and the build fails outright with no graceful degradation.
  • ✓The runtime function is byte-for-byte the JavaScript one after erasure, zero difference. The compile-time Permutation<T> type has a real, separate cost: every one of the n!

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 TypeScript: what you actually reach for

Runtime: nothing, same gap as JavaScript. Type-level: TypeScript's recursive conditional types can compute every permutation of a literal union entirely at compile time, something no other language here does purely in its type system, `type Permutation<T, K = T> = [T] extends [never] ? [] : K extends K ? [K, ...Permutation<Exclude<T, K>>] : never` produces a union of every tuple ordering of a string/number literal union, with zero runtime code. The mechanism is DISTRIBUTIVE conditional types: because K is a bare, unwrapped type parameter on the left of extends inside `K extends K`, the compiler distributes the conditional over each union member separately instead of treating K as one opaque blob, which is exactly what lets the type visit each member as the 'next chosen element' in turn; wrapping the base case as `[T] extends [never]` rather than `T extends never` is the standard trick to turn distribution OFF for that one check.

TypeScript implementation

Type the runtime swap-based function's return as T[][], not any[][], generics carry through cleanly since the function never inspects T's shape, only moves it around, so `function permutations<T>(items: T[]): T[][]` costs nothing and gives every caller full inference. Reach for the compile-time Permutation<T> type only when the input is a small, known, literal union (route names, a fixed CSS property list), it is a documentation and exhaustiveness tool, not a runtime algorithm.
typescript
type Permutation<T, K = T> = [T] extends [never]
  ? []
  : K extends K
    ? [K, ...Permutation<Exclude<T, K>>]
    : never;

type Direction = Permutation<'north' | 'south' | 'east' | 'west'>;
// compile-time-only: a union of every 4! = 24 tuple orderings, zero runtime cost

function permutations<T>(items: T[]): T[][] {
  const result: T[][] = [];
  const arr = items.slice();

  function recurse(k: number): void {
    if (k === arr.length) {
      result.push(arr.slice());
      return;
    }
    for (let i = k; i < arr.length; i += 1) {
      [arr[k], arr[i]] = [arr[i], arr[k]];
      recurse(k + 1);
      [arr[k], arr[i]] = [arr[i], arr[k]];
    }
  }

  recurse(0);
  return result;
}

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 TypeScript-specific trap

The compile-time Permutation<T> type is a recursive conditional type, and tsc has a real recursion-depth ceiling: in practice, past roughly single-digit union sizes (9 members is already 362,880 tuple types) you hit 'Type instantiation is excessively deep and possibly infinite,' and the build fails outright with no graceful degradation. The type-level trick that looks like a superpower for a 3-4-member union is unusable for anything the runtime function would consider a completely ordinary input size.

Performance in TypeScript, beyond the O(n!)

The runtime function is byte-for-byte the JavaScript one after erasure, zero difference. The compile-time Permutation<T> type has a real, separate cost: every one of the n! tuple types has to be constructed and cached during type-checking, which is exactly the kind of type-level computation that shows up as a slow `tsc --noEmit` in CI on a codebase that overuses recursive conditional types, independent of how fast the actual built JavaScript runs. 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 TypeScript, 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 TypeScript, demonstrate proficiency with generics and type guards to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic TypeScript code that is both correct and maintainable.

Frequently Asked Questions

Which TypeScript type or library should I use for Permutations?

Runtime: nothing, same gap as JavaScript. Type-level: TypeScript's recursive conditional types can compute every permutation of a literal union entirely at compile time, something no other language here does purely in its type system, `type Permutation<T, K = T> = [T] extends [never] ? [] : K extends K ? [K, ...Permutation<Exclude<T, K>>] : never` produces a union of every tuple ordering of a string/number literal union, with zero runtime code. The mechanism is DISTRIBUTIVE conditional types: because K is a bare, unwrapped type parameter on the left of extends inside `K extends K`, the compiler distributes the conditional over each union member separately instead of treating K as one opaque blob, which is exactly what lets the type visit each member as the 'next chosen element' in turn; wrapping the base case as `[T] extends [never]` rather than `T extends never` is the standard trick to turn distribution OFF for that one check.

What is the most common TypeScript mistake when implementing Permutations?

The compile-time Permutation<T> type is a recursive conditional type, and tsc has a real recursion-depth ceiling: in practice, past roughly single-digit union sizes (9 members is already 362,880 tuple types) you hit 'Type instantiation is excessively deep and possibly infinite,' and the build fails outright with no graceful degradation. The type-level trick that looks like a superpower for a 3-4-member union is unusable for anything the runtime function would consider a completely ordinary input size.

How does Permutations actually perform in TypeScript?

The runtime function is byte-for-byte the JavaScript one after erasure, zero difference. The compile-time Permutation<T> type has a real, separate cost: every one of the n! tuple types has to be constructed and cached during type-checking, which is exactly the kind of type-level computation that shows up as a slow `tsc --noEmit` in CI on a codebase that overuses recursive conditional types, independent of how fast the actual built JavaScript runs. 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

If you are a student, see what Devin offers students for free 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.