GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #60 - Permutation Sequence - LeetCode JavaScript Solutions

Back to all solutions

#60 - Permutation Sequence

Hard • View on LeetCode • View on GitHub
Math Recursion

Problem Description

The set [1, 2, 3, ..., n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order, we get the following sequence for n = 3:

  • "123"
  • "132"
  • "213"
  • "231"
  • "312"
  • "321"

Given n and k, return the kth permutation sequence.

Solution

/**
 * @param {number} n
 * @param {number} k
 * @return {string}
 */
var getPermutation = function(n, k) {
  const factorial = [1];
  for (let i = 1; i < n; i++) {
    factorial[i] = factorial[i-1] * i;
  }

  const values = new Array(n).fill(0).map((_, i) => i + 1);
  let result = '';
  k--;

  for (let i = n - 1; i >= 0; i--) {
    const index = Math.floor(k / factorial[i]);
    k = k % factorial[i];
    result += values[index];
    values.splice(index, 1);
  }

  return result;
};
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.