• + 0 comments

    import java.io.; import java.util.; import java.util.stream.*;

    class Result {

    public static String biggerIsGreater(String w) {
        char[] chars = w.toCharArray();
        int i = chars.length - 2;
    
        // Step 1: Find the first character that is smaller than its next character from the end
        while (i >= 0 && chars[i] >= chars[i + 1]) {
            i--;
        }
    
        if (i < 0) {
            return "no answer";
        }
    
        // Step 2: Find the smallest character on the right of i that is greater than chars[i]
        int j = chars.length - 1;
        while (chars[j] <= chars[i]) {
            j--;
        }
    
        // Step 3: Swap them
        char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
    
        // Step 4: Reverse the suffix starting at i + 1
        int left = i + 1, right = chars.length - 1;
        while (left < right) {
            temp = chars[left];
            chars[left] = chars[right];
            chars[right] = temp;
            left++;
            right--;
        }
    
        return new String(chars);
    }
    

    }

    public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int T = Integer.parseInt(bufferedReader.readLine().trim());
    
        IntStream.range(0, T).forEach(TItr -> {
            try {
                String w = bufferedReader.readLine();
                String result = Result.biggerIsGreater(w);
                bufferedWriter.write(result);
                bufferedWriter.newLine();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
    
        bufferedReader.close();
        bufferedWriter.close();
    }
    

    }