Next Permutation in TypeScript

function nextPermutation(nums: number[]): void {
    // Step 1: Find the pivot
    let i = nums.length - 1;
    while (i > 0 && nums[i - 1] >= nums[i]) {
        i--;
    }

    if (i > 0) {
        // Step 2: Find the successor to pivot
        let j = nums.length - 1;
        while (nums[j] <= nums[i - 1]) {
            j--;
        }

        // Step 3: Swap
        [nums[i - 1], nums[j]] = [nums[j], nums[i - 1]];
    }

    // Reverse the elements from i to the end of the array
    reverse(nums, i, nums.length - 1);
}

function reverse(nums: number[], start: number, end: number): void {
    while (start < end) {
        [nums[start], nums[end]] = [nums[end], nums[start]];
        start++;
        end--;
    }
}

PrevNext