Data Structures & Algorithms

Leetcode 31 Next Permutation Java Solution

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 and use only constant 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

Solution 1:

class Solution {
    public void nextPermutation(int[] nums) {
        if(nums == null || nums.length <=1) return;
        
        int permIndex = -1;
        for(int i=nums.length-1;i>=1;i--){
            if(nums[i-1] <nums[i]){
                permIndex = i-1;
                break;
            }
        }
        
        //reverse if permIndex = -1
        
        if(permIndex == -1){
            reverse(nums, 0, nums.length-1);
            return;
        }
        
        //if permIndex+1 = nums.length-1 swap n-1,n
        
        if(permIndex!=-1 && permIndex+1 == nums.length-1){
            swap(nums, permIndex, permIndex+1);
            return;
        }
        
        int tempValue = nums[permIndex];
        int nextGreaterElementIndex = Integer.MIN_VALUE;
        
        for(int i=nums.length-1;i>=permIndex+1;i--){
            if(nums[i]>nums[permIndex]){
                nextGreaterElementIndex = i;
                break;
            }
        }
        
        swap(nums, permIndex, nextGreaterElementIndex);
        reverse(nums, permIndex+1, nums.length-1);
    }
    
    
    private void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
    
    private void reverse(int[] nums, int i, int j){
        
        while(i<j){
            swap(nums, i++, j--);
        }
        
        return;
    }
}

rajendra

Recent Posts

Largest Unique Number Java Solution

Question : Given an array of integers A, return the largest integer that only occurs once.…

10 months ago

Jump Search Algorithm In Java

Jump search algorithm is a pretty new algorithm to search for an element in a…

1 year ago

Knuth Morris Pratt Pattern Search Algorithm

What is Knuth Morris Pratt or KMP algorithm ? KMP is an algorithm which is…

1 year ago

Binary Search Algorithm In Java

Binary Search is a Logarithmic search which finds the target element in a sorted array…

1 year ago

Leetcode Integer to Roman Java Solution

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X…

2 years ago

Leetcode Container With Most Water Java Solution

Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such…

2 years ago

This website uses cookies.