package java_programs;
import java.util.*;

public class NEXT_PERMUTATION {
    public static ArrayList<Integer> next_permutation(ArrayList<Integer> perm) {
        int k = -1;
        for (int i = perm.size() - 2; i >= 0; i--) {
            if (perm.get(i) < perm.get(i + 1)) {
                k = i;
                break;
            }
        }

        if (k == -1) {
            Collections.sort(perm);
            return perm;
        }

        int l = perm.size() - 1;
        while (perm.get(k) >= perm.get(l)) {
            l--;
        }

        int temp = perm.get(k);
        perm.set(k, perm.get(l));
        perm.set(l, temp);

        int start = k + 1;
        int end = perm.size() - 1;
        while (start < end) {
            temp = perm.get(start);
            perm.set(start, perm.get(end));
            perm.set(end, temp);
            start++;
            end--;
        }

        return perm;
    }
}