MCPcopy
hub / github.com/mgechev/google-interview-preparation-problems / nextPermutation

Function nextPermutation

src/next-permutation.js:23–39  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

21};
22
23const nextPermutation = a => {
24 let smaller = -1;
25 for (let i = a.length - 1; i > 0; i -= 1) {
26 if (a[i] > a[i - 1]) {
27 smaller = i - 1;
28 break;
29 }
30 }
31 if (smaller === -1) {
32 a.sort((a, b) => a - b);
33 return;
34 }
35 let swapIdx = smaller + 1;
36 while (swapIdx < a.length && a[swapIdx] > a[smaller]) swapIdx++;
37 swap(a, smaller, swapIdx - 1);
38 sort(a, smaller + 1);
39};
40
41const a = [1, 2, 3];
42console.log([1, 2, 3]);

Callers 1

Calls 2

swapFunction · 0.70
sortFunction · 0.70

Tested by

no test coverage detected