IBM | OA 2021 | Next Permutation
Anonymous User
2338

image
image

This is pretty much https://leetcode.com/problems/next-permutation/

class Result {
    public static String rearrangeWord(String word) {
        // Write your code here
        StringBuilder sb = new StringBuilder(word);

        int i = sb.length() - 2;

        // find the position where the char at i + 1 > char at i
        while (i >= 0 && (sb.charAt(i + 1) <= sb.charAt(i))) {
            i--;
        }

        if (i < 0) {
            return sb.toString().compareTo(word) == 0 ? "no answer" : sb.toString();
        }

        // if the string is not entirely descending
        // start from end and find char at j > char at i
        // swap char i j
        int j = sb.length() - 1;

        while (j >= 0 && (sb.charAt(j) <= sb.charAt(i))) {
            j--;
        }

        swap(sb, i, j);

        // reverse descending sequence
        reverse(sb, i + 1, sb.length() - 1);

        return sb.toString().compareTo(word) == 0 ? "no answer" : sb.toString();
    }

    static void swap(StringBuilder sb, int i, int j) {
        char tmp = sb.charAt(j);
        sb.setCharAt(j, sb.charAt(i));
        sb.setCharAt(i, tmp);

    }
 
    static void reverse(StringBuilder sb, int start) {
        int end = sb.length() - 1;

        while (start < end) {
            swap(sb, start, end);
            start++;
            end--;
        }
    }
}
Comments (4)