Next permutation-Coding question asked by Sprinklr, Goldmann Sachs
Given an array of integers nums, find the next permutation of nums.
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer
Number of Rows in Pascal Triangle
List containing arrays representing rows of Pascal Triangle
Sample Input 1:
Sample Output 1:
Sample Input 2:
Sample Output 2:
1 <= nums.length <= 1000 <= nums[i] <= 100
- Start iterating from backwards.
- Find an index i-th such that nums[i]>nums[i-1]. Now on the right side of nums[i-1], you need to find an index j, such that nums[j] is just larger that nums[i-1]. For this, sort the array after nums[i-1] first.
- Swap nums[i-1] & nums[j]. Sort the array after nums[i-1] again.
- If iterator has reached first element position, it means no more permutations in increasing lexicographic order are possible, i.e. descending order is there. Therefore, reverse the array for this case.
Time complexity: O(n)
Space complexity: O(1)
Thanks for Reading
Placewit grows the best engineers by providing an interactive classroom experience and by helping them develop their skills and get placed in amazing companies.