Welcome To Golang By Example

Find the next permutation of a number in Go (Golang)

Table of Contents

Overview

The objective is to find the next permutation of a given number based upon lexicographical sorting order. If the next permutation is not possible then return the same number

For eg

Input: [1,2,3]
Output: [1,3,2]

Input: [2,1]
Output: [2,1]

Input: [1, 3, 5, 4, 1]
Output: [1, 4, 1, 3, 5]


Input: [1, 3, 2]
Output: [2, 1, 3]

Below will be the strategy

Program

Below is the program for the same

package main

import (
	"fmt"
	"sort"
)

func main() {
	nextPermutation([]int{1, 2, 3})

	nextPermutation([]int{2, 1})

	nextPermutation([]int{1, 3, 5, 4, 1})

	nextPermutation([]int{1, 3, 2})
}

func nextPermutation(nums []int) {

	numsLen := len(nums)
	first := -1
	second := -1

	for i, j := numsLen-2, numsLen-1; i >= 0; {
		if nums[i] < nums[j] {
			first = i
			second = j
			break
		} else {
			i--
			j--
		}
	}

	if !(first == -1) {
		smallestGreaterIndex := second
		for i := second + 1; i < numsLen; i++ {
			if nums[i] > nums[first] && nums[i] < nums[smallestGreaterIndex] {
				smallestGreaterIndex = i
			}
		}
		nums[first], nums[smallestGreaterIndex] = nums[smallestGreaterIndex], nums[first]

		sort.Slice(nums[second:numsLen], func(i, j int) bool {
			return nums[second+i] < nums[second+j]
		})
	}

	fmt.Println(nums)

}

Output

[1 3 2]
[2 1]
[1 4 1 3 5]
[2 1 3]

Note: Check out our Golang Advanced Tutorial. The tutorials in this series are elaborative and we have tried to cover all concepts with examples. This tutorial is for those who are looking to gain expertise and a solid understanding of golang - Golang Advance Tutorial

Also if you are interested in understanding how all design patterns can be implemented in Golang. If yes, then this post is for you -All Design Patterns Golang