Skip to content

Commit 86b2646

Browse files
author
Ashef Habib Tishad
committed
Update 031-Next Permutation
Changes: ---------- * Devided resposiblity with using functions. * Slice in already a reference type in go, means in passes actual slice(not a copy) to functions, that's why using pointers in swap and reverse functions look redundant in my opinion. Discussion: -------------- https://leetcode.com/problems/next-permutation/discuss/1554932/Go-Submission-with-Explanation
1 parent af654b2 commit 86b2646

File tree

1 file changed

+43
-19
lines changed

1 file changed

+43
-19
lines changed
Lines changed: 43 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,55 @@
1+
// https://leetcode.com/problems/next-permutation/discuss/1554932/Go-Submission-with-Explanation
2+
// Time O(N) , Space: O(1)
3+
14
package leetcode
25

6+
// [2,(3),6,5,4,1] -> 2,(4),6,5,(3),1 -> 2,4, 1,3,5,6
37
func nextPermutation(nums []int) {
4-
i, j := 0, 0
5-
for i = len(nums) - 2; i >= 0; i-- {
6-
if nums[i] < nums[i+1] {
7-
break
8-
}
8+
var n = len(nums)
9+
var pIdx = checkPermutationPossibility(nums)
10+
if pIdx == -1 {
11+
reverse(nums, 0, n-1)
12+
return
913
}
10-
if i >= 0 {
11-
for j = len(nums) - 1; j > i; j-- {
12-
if nums[j] > nums[i] {
13-
break
14-
}
14+
15+
var rp = len(nums) - 1
16+
// start from right most to leftward,find the first number which is larger than PIVOT
17+
for rp > 0 {
18+
if nums[rp] > nums[pIdx] {
19+
swap(nums, pIdx, rp)
20+
break
21+
} else {
22+
rp--
1523
}
16-
swap(&nums, i, j)
1724
}
18-
reverse(&nums, i+1, len(nums)-1)
25+
// Finally, Reverse all elements which are right from pivot
26+
reverse(nums, pIdx+1, n-1)
1927
}
2028

21-
func reverse(nums *[]int, i, j int) {
22-
for i < j {
23-
swap(nums, i, j)
24-
i++
25-
j--
29+
func swap(nums []int, i, j int) {
30+
nums[i], nums[j] = nums[j], nums[i]
31+
}
32+
33+
func reverse(nums []int, s int, e int) {
34+
for s < e {
35+
swap(nums, s, e)
36+
s++
37+
e--
2638
}
2739
}
2840

29-
func swap(nums *[]int, i, j int) {
30-
(*nums)[i], (*nums)[j] = (*nums)[j], (*nums)[i]
41+
// checkPermutationPossibility returns 1st occurrence Index where
42+
// value is in decreasing order(from right to left)
43+
// returns -1 if not found(it's already in its last permutation)
44+
func checkPermutationPossibility(nums []int) (idx int) {
45+
// search right to left for 1st number(from right) that is not in increasing order
46+
var rp = len(nums) - 1
47+
for rp > 0 {
48+
if nums[rp-1] < nums[rp] {
49+
idx = rp - 1
50+
return idx
51+
}
52+
rp--
53+
}
54+
return -1
3155
}

0 commit comments

Comments
 (0)