
Sponsored
Sponsored
This approach involves transforming the current permutation into its next lexicographical order. The key operations include identifying the longest non-increasing suffix and swapping elements to get a slightly larger permutation, followed by reversing the suffix to get the lowest order.
Time Complexity: O(n), where n is the number of elements in the array. This is due to the maximal traversal and operations over the array.
Space Complexity: O(1) since the operation is performed in-place with constant memory usage.
1function nextPermutation(nums) {
2 let i = nums.length - 2;
3 while (i >= 0 && nums[i] >= nums[i + 1]) i--;
4 if (i >= 0) {
5 let j = nums.length - 1;
6 while (nums[j] <= nums[i]) j--;
7 [nums[i], nums[j]] = [nums[j], nums[i]];
8 }
9 reverse(nums, i + 1);
10}
11
12function reverse(nums, start) {
13 let end = nums.length - 1;
14 while (start < end) {
15 [nums[start], nums[end]] = [nums[end], nums[start]];
16 start++;
17 end--;
18 }
19}
20
21let nums = [1, 2, 3];
22nextPermutation(nums);
23console.log(nums);The JavaScript solution hinges on logical array traversals, utilizing intuitive swaps, thereby achieving rearrangement through native capabilities sans additional resource usage.