Leetcode–Next Permutation

The Problem:

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


  1. A tricky question that I think is too hard for an interview if haven’t met it before, it’s a classic one though.
  2. Steps:
    1. For an always descending array, it’s simple that only need to sort the array in ascending order.
    2. Otherwise means It has ascending pair somewhere, find the last index that with a larger number following. Note that beyond that “last index”, the array is in descending order. Then reverse the descending half to make it in ascending order, and swap the “last index” number with the smallest one that is greater than it in the latter half.

Java Solution

public class Solution {
    public void nextPermutation(int[] num) {
        if(num.length <=1)return;

        int indexInc = -1;
        for(int i = 1; i< num.length; i++){
            if(num[i] > num[i-1]){
                indexInc = i-1;
        if(indexInc ==-1){
            // decreaseing all the way
            int i = indexInc+1;
            int j = num.length-1;
                int temp = num[i];
                num[i] = num[j];
                num[j] = temp;
            for(int k = indexInc+1; k<num.length; k++){
                if(num[k] > num[indexInc]){
                    int temp = num[k];
                    num[k] = num[indexInc];
                    num[indexInc] = temp;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s