Next Permutation - Golang
Problem statement:
A permutation of an array of integers is an arrangement of its members into a sequence or linear order.
The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array were sorted in one container, the next permutation is the next one in the sorted order. If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).
Given an array of integers nums, replace nums with its next permutation in-place.
Example:
Input:
[1,2,3]
Expected output:
[1,3,2]
Example 2:
Input:
[3,2,1]
Expected output:
[1,2,3]
Example 3:
Input:
[1,1,5]
Expected output:
[1,5,1]
If you would like to solve the problem on Leetcode, here is the link to the problem: https://leetcode.com/problems/next-permutation/
Golang Solution:
func nextPermutation(nums []int) {
i := len(nums) - 2
for i >= 0 && nums[i] >= nums[i+1] {
i -= 1
}
if i >= 0 {
j := len(nums) - 1
for nums[j] <= nums[i] {
j -= 1
}
swap(nums, i, j)
}
reverse(nums, i+1)
}
func reverse(nums []int, start int) {
i, j := start, len(nums)-1
for i < j {
swap(nums, i, j)
i++
j--
}
}
func swap(nums []int, i int, j int) {
nums[i], nums[j] = nums[j], nums[i]
}
