Optimal Approach
If we observe the pattern, we find that in all these generated permutations, there exists an index such that the part to its right is decreasingly sorted. On traversing the array backward (from n-1), it is sorted in ascending order till this index i.
Algorithm:
- Traverse through the array from the end (n-1).
- Find an element that is smaller than its right neighbor. Let’s call it arr[i].
- In case no such element is found, that means the array is sorted in decreasing order. This indicates that it is the largest possible permutation of the array. So we return the reverse of the array as the next permutation.
- Once we find arr[i], we need to find the smallest element to its right that is greater than arr[i]. We will call that element as arr[j].
- Now swap arr[i] and arr[j].
- Reverse the part of the array to the right of arr[i]. That means from indices i+1 to n-1.
- Return the array and print the answer.
Example: Below is the implementation of the above approach
Javascript
// Function to find the next permutation function nextPermutation(arr) { const n = arr.length; let idx = -1; // Find the element from right that // is smaller than its right neighbor for (let i = n - 2; i >= 0; i--) { if (arr[i] < arr[i + 1]) { // index i is the element to be swapped idx = i; break ; } } // If no such element exists, reverse // it to get the smallest permutation if (idx === -1) { arr.reverse(); return arr; } // Find the smallest element as per the above approach for (let j = n - 1; j > idx; j--) { if (arr[j] > arr[idx]) { // index j is the element to be swapped [arr[j], arr[idx]] = [arr[idx], arr[j]]; break ; } } // Reverse the part to the right of arr[i] let left = idx + 1; let right = n - 1; while (left < right) { [arr[left], arr[right]] = [arr[right], arr[left]]; left++; right--; } return arr; } // Input const arr = [5, 2, 9, 8]; const ans = nextPermutation(arr); console.log(ans); |
Output
[ 5, 8, 2, 9 ]
Time Complexity: O(N)
Space Complexity: O(1)
JavaScript Program to Find Lexicographically Next Permutation
Given an array of distinct integers, we want to find the lexicographically next permutation of those elements. In simple words, when all the possible permutations of an array are placed in a sorted order, it is the lexicographic order of those permutations. In this case, we have to find the next greater permutation of the elements in this sorted or lexicographic order.
Examples:
Example 1:
Input: [1, 2, 3]
Output: [1, 3, 2]
Explanation: If all the permutations of these elements are arranged in a sorted order:
[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]
Here, next greater permutation of [1, 2, 3] is [1, 3, 2].
Example 2:
Input: [6, 3, 4, 7, 1] Output: [6, 3, 7, 1, 4] Explanation: If all the permutations of these elements are arranged in a sorted order, next greater permutation of [6, 3, 4, 7, 1] is [6, 3, 7, 1, 4].
Table of Content
- Brute Force Approach
- Optimal Approach