31. Next Permutation

ArrayTwo Pointers

Explanation

To find the next lexicographically greater permutation of an array, we can follow these steps:

  1. Traverse the array from right to left to find the first element (let's call it pivot) that is smaller than the element to its right.
  2. If such a pivot exists, find the smallest element to the right of pivot that is greater than pivot. Swap pivot with this element.
  3. Reverse the subarray to the right of the pivot to get the next permutation.
  4. If no such pivot exists, it means the array is in descending order, so we reverse the entire array to get the lowest possible order (ascending order).

Time complexity: O(n) where n is the length of the array. Space complexity: O(1) as no extra memory is used.

class Solution {
    public void nextPermutation(int[] nums) {
        int i = nums.length - 2;
        while (i >= 0 && nums[i] >= nums[i + 1]) {
            i--;
        }
        if (i >= 0) {
            int j = nums.length - 1;
            while (j >= 0 && nums[j] <= nums[i]) {
                j--;
            }
            swap(nums, i, j);
        }
        reverse(nums, i + 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 start) {
        int end = nums.length - 1;
        while (start < end) {
            swap(nums, start, end);
            start++;
            end--;
        }
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.