Next permutation-Coding question asked by Sprinklr, Goldmann Sachs

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:

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.

Learn more at Placewit. Follow us on Instagram and Facebook for daily learning

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store