JavaScript Program to Find Lexicographically Next Permutation
Last Updated :
07 Nov, 2023
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].
Approach 1: Brute Force Approach
As a brute force approach, we can generate all the possible permutations of the given array and store all the generated sequences. Then we sort all these arrays in increasing order and find the lexicographically next permutation by a simple searching technique.
Algorithm:
- Create a recursive function called permute that generates all the possible permutations of the given array by swapping the elements.
- Keep storing the generated combinations in another array named as total.
- Then iterate through this array and compare each one to the input array to find a match.
- Use JSON.stringify to compare the arrays.
- Once we find our input array, just return the next array in the traversal which will be our lexicographically next permutation.
- In a case, if there is no such permutation, we print a message that states no permutation possible.
Example: Below is the implementation of the above approach
JavaScript
// JavaScript code for the above approach
// Recursive function to generate all permutations
const permute = (arr, idx, res) => {
// Base case
if (idx === arr.length - 1) {
res.push([...arr]);
return;
}
const n = arr.length;
// Iterate the array starting from the new index
for (let i = idx; i < n; i++) {
// Swap the elements
[arr[idx], arr[i]] = [arr[i], arr[idx]];
// Make a recursive call
permute(arr, idx + 1, res);
// Backtrack
[arr[idx], arr[i]] = [arr[i], arr[idx]];
}
};
// Function to call the recursive function
function generatePermutations(arr) {
const res = [];
permute(arr, 0, res);
return res;
}
// Input
let arr = [1, 2, 3];
let total = generatePermutations(arr);
const n = total.length;
// Sort the permutations' array
total.sort();
let ans = null;
// Check if the input array is
// the largest possible permutation
if (JSON.stringify(total[n - 1]) ===
JSON.stringify(arr)) {
// If yes, then the next permutation
// is the smallest permutation
ans = total[0];
}
// Find the next permutation
for (let i = 0; i < n - 1; i++) {
if (JSON.stringify(total[i]) ===
JSON.stringify(arr)) {
ans = total[i + 1];
break;
}
}
// Print the answer
if (ans) {
console.log(ans);
}
else {
console.log("No next permutation found");
}
Time Complexity: O(N!*N)
Space Complexity: O(1)
Method 2: 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);
Time Complexity: O(N)
Space Complexity: O(1)
Similar Reads
JavaScript Program to find Lexicographically next String
In this article, we are going to learn how can we find the Lexicographically next string. Lexicographically next string refers to finding the string that follows a given string in a dictionary or alphabetical order.Examples: Input : testOutput : tesuExplanation : The last character 't' is changed to
3 min read
JavaScript Program to Find Lexicographically Next String
In this article, we are going to learn about Lexicographically next string in JavaScript. A lexicographically next string is the immediate string in a sorted order that comes after a given string when considering character sequences. It's determined by rearranging characters to find the smallest cha
3 min read
JavaScript Program to Find Power Set in Lexicographic Order
Power set P(S) of a set S is the set of all subsets of S. For example S = {1, 2, 3} then P(s) = {{}, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}}.This JavaScript code generates and sorts the power set of an input string in lexicographic order, listing all possible subsets from the empty set to the f
6 min read
JavaScript Program to Calculate nPr (Permutations)
In this article, we are going to learn how to calculate permutations (nPr) by using JavaScript. Calculating nPr, or permutations means finding the number of unique ordered arrangements of r items from a set of n distinct items. Where order matters and no item is repeated. The formula for calculating
3 min read
JavaScript Program to Print all Palindromic Paths from Top Left to Bottom Right in a Matrix
We are given a matrix containing only lower-case alphabetical characters. The task is to print all the palindromic paths present in the given matrix. A path is a sequence of cells starting from the top-left cell and ending at the bottom-right cell. We are allowed to move only to the right and down f
4 min read
JavaScript Program to Print all Possible Strings that can be Made by Placing Spaces
In this article, We are going to see how can we print all possible strings that can be made by placing spaces. We will add spaces in between the strings and print every possible value. Example: Input: "ABCD"Output: 'A B C D' 'A B CD' 'A BC D' 'A BCD' 'AB C D' 'AB CD' 'ABC D' 'ABCD'Table of Content B
5 min read
JavaScript Program for Insertion Sort
What is Insertion Sort Algorithm?Insertion sorting is one of the sorting techniques that is based on iterating the array and finding the right position for every element. It compares the current element to the predecessors, if the element is small compare it with the elements before. Move ahead to a
4 min read
JavaScript Program to Search a Word in a 2D Grid of Characters
In this article, we will solve a problem in which you are given a grid, with characters arranged in a two-layout(2D). You need to check whether a given word is present in the grid. A word can be matched in all 8 directions at any point. Word is said to be found in a direction if all characters match
7 min read
Javascript Program to FInd Lexicographically smallest rotated sequence | Set 2
Write code to find lexicographic minimum in a circular array, e.g. for the array BCABDADAB, the lexicographic minimum is ABBCABDADInput Constraint: 1 < n < 1000 Examples: Input: GEEKSQUIZOutput: EEKSQUIZGInput: GFGOutput: FGGInput : CAPABCQOutput : ABCQCAPWe have discussed a O(n2Logn) solution
2 min read
Lexicographically smallest Permutation of Array by reversing at most one Subarray
Given an array arr[] of size N which is a permutation from 1 to N, the task is to find the lexicographically smallest permutation that can be formed by reversing at most one subarray. Examples: Input : arr[] = {1, 3, 4, 2, 5}Output : 1 2 4 3 5Explanation: The subarray from index 1 to index 3 can be
8 min read