Here is the full solution:
function nextPermutation(nums)
n := length of nums
pivot := -1
// Find pivot
for i from n-2 down to 0
if nums[i] < nums[i+1] then
pivot := i
break
if pivot = -1 then
reverse(nums, 0, n-1)
return
// Find successor
for j from n-1 down to pivot+1
if nums[j] > nums[pivot] then
swap(nums[pivot], nums[j])
break
// Reverse suffix
reverse(nums, pivot+1, n-1)
Time: . Space: . All operations are linear scans or in-place swaps.