Next Permutation

You have been given a permutation of ‘N’ integers. A sequence of ‘N’ integers is called a permutation if it contains all integers from 1 to ‘N’ exactly once. Your task is to rearrange the numbers and generate the lexicographically next greater permutation.

To determine which of the two permutations is lexicographically smaller, we compare their first elements of both permutations. If they are equal — compare the second, and so on. If we have two permutations X and Y, then X is lexicographically smaller if X[i] < Y[i], where ‘i’ is the first index in which the permutations X and Y differ.

For example, [2, 1, 3, 4] is lexicographically smaller than [2, 1, 4, 3].

Input Format:
The first line contains a single integer ‘T’ representing the number of test cases. 

The first line of each test case will contain an integer ‘N’ representing the length of the permutation.

The second line contains ‘N’ space-separated integers which are the elements of the permutation.
Output Format:
For each test case, print the elements of the lexicographically next greater permutation with a single space-separated. If lexicographically next greater permutation doesn’t exist, print the lexicographically smallest permutation.

Output for every test case will be printed in a separate line.
Note:
You do not need to print anything; It has already been taken care of.
Constraints:
1 <= T <= 50
1 <= N <= 10000
1 <= P[i] <= N

Time limit: 1 sec
CodingNinjas
author
2y

Approach :
1) Find the first pair of two successive numbers a[i] and a[i-1] , from the right, which satisfy a[i] > a[i−1].
2) Rearrange the numbers to the right of a[i-1] including itself.
3) Replace th...read more

CodingNinjas
author
2y
Brute Force

The basic idea is to generate all the possible permutations of ‘N’ integers and find the lexicographically next greater permutation.

Steps are as follows:

  1. Generate all the possible permutati...read more
CodingNinjas
author
2y
Greedy

The basic idea of this approach is to develop a greedy algorithm to find the lexicographically next greater permutation.

First of all, note that a permutation of integers which is sorted in desce...read more

Add answer anonymously...
Nagarro Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter