You are on page 1of 3

Problem Name: Next Permutation

Problem Difficulty: 2
Problem Constraints: 1 <= T <= 100 <br>
1 <= N <= 1000 <br>
0 <= A<sub>i</sub> <= 9
Problem Description:
Given an array Arr[], Treat each element of the array as the digit and whole array
as the number. Implement the next permutation, which rearranges numbers into the
numerically next greater permutation of numbers.

If such arrangement is not possible, it must be rearranged as the lowest possible


order ie, sorted in an ascending order.

__Note:__ The replacement must be in-place, do not allocate extra memory.


Input Format: The First Line contains the Number of test cases T. <br>
Next Line contains an Integer N, number of digits of the number. <br>
Next Line contains N-space separated integers which are elements of the array
'Arr'.
Sample Input: 2
3
1 2 3
3
3 2 1

Output Format: Print the Next Permutation for each number separated by a new Line.
Sample Output: 1 3 2
1 2 3

=====Solution=====
import java.util.*;
public class Main {

static Scanner scn = new Scanner(System.in);

public static void main(String args[]) {

int t = scn.nextInt();
while ((t--) > 0) {

int n = scn.nextInt();
int[] arr = takeInput(n);

next_permutation(arr);
display(arr);

}
}

public static int[] takeInput(int n) {

int[] arr = new int[n];

for (int i = 0; i < arr.length; i++)


arr[i] = scn.nextInt();
return arr;

public static void next_permutation(int[] nums) {

if (nums == null || nums.length < 2)


return;

int p = 0;
for (int i = nums.length - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
p = i;
break;
}
}

int q = 0;
for (int i = nums.length - 1; i > p; i--) {
if (nums[i] > nums[p]) {
q = i;
break;
}
}

if (p == 0 && q == 0) {
reverse(nums, 0, nums.length - 1);
return;
}

int temp = nums[p];


nums[p] = nums[q];
nums[q] = temp;

if (p < nums.length - 1) {
reverse(nums, p + 1, nums.length - 1);
}
}

public static void reverse(int[] nums, int left, int right) {


while (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}

public static void display(int[] arr) {

for (int val : arr) {


System.out.print(val + " ");
}

System.out.println();
}
}

You might also like