# Problem Statement:

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

Input Format:

Output Format:

Sample Input 1:

Sample Output 1:

Sample Input 2:

Sample Output 2:

Constraints:

# Approach:

1. Start iterating from backwards.
2. 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.
3. Swap nums[i-1] & nums[j]. Sort the array after nums[i-1] again.
4. 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)

# Code:

Placewit grows the best engineers by providing an interactive classroom experience and by helping them develop their skills and get placed in amazing companies.

--

--

## More from Placewit

Upskilling students for tech placements!

Love podcasts or audiobooks? Learn on the go with our new app.