Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Next Permutation

Posted on March 18, 2018July 26, 2020 by braindenny

Next Permutation



Similar Problems:

  • Permutation Sequence
  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #nextpermutation, #greedy, #constructstring

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,3 -> 1,3,2
3,2,1 -> 1,2,3
1,1,5 -> 1,5,1

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


Related Readings:

  • Next lexicographical permutation algorithm
  • Wikipedia:Permutation

Leetcode: Next Permutation

Leetcode: Next Permutation

// https://code.dennyzhang.com/next-permutation
// Basic Ideas:
//   1. From right to left, find the longest non-increasing subsequence
//   2. Swap items
//   3. Reverse the subsequence
//
//   0 1 2 5 3 3 0
//   0 1 3 5 3 2 0
//   0 1 3 0 2 3 5
// Complexity:
func nextPermutation(nums []int)  {
    if len(nums) == 0 {
        return
    }
    var i = len(nums) - 2
    for ; i>=0; i-- {
        if nums[i] < nums[i+1] {
            break
        }
    }
    if i == -1 {
        sort.Ints(nums)
        return
    }
    var index = i
    // find element to swap
    i = len(nums) - 1
    for ; i>=0; i-- {
        if nums[i] > nums[index] {
            break
        }
    }
    nums[i], nums[index] = nums[index], nums[i]
    // reverse
    var l, r = index+1, len(nums)-1
    for l<r {
        nums[l], nums[r] = nums[r], nums[l]
        l, r = l+1, r-1
    }
}
linkedin
github
slack

Post Views: 10
Posted in MediumTagged #combination, #greedy, constructstring, nextpermutation

Post navigation

LintCode: Prime Product
LeetCode: Unique Morse Code Words

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.