import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    public static int solution(String n, int b) {
        List<String> cycle = new ArrayList<>();
        List<String> prevCycle = null;

        int k = n.length();
        
        boolean repeat = false;
        while (!repeat) {
            //obtain sorted x and y
            char[] chars = n.toCharArray();
            Arrays.sort(chars);
            String y = new String(chars);  //y is ascending, not x

            StringBuilder sb = new StringBuilder(y);
            String x = sb.reverse().toString();

            //calculate z with base
            int z = Integer.parseInt(x, b) - Integer.parseInt(y, b);
            //obtain n with base 
            n = Integer.toString(z, b);

            //prepend zeroes
            int prependCount = k - n.length();
            if (prependCount > 0) {
                char[] prepend = new char[prependCount];
                Arrays.fill(prepend, '0');
                n = new String(prepend) + n;
            }
            
            //check if we are in a cycle
            int search = cycle.indexOf(n);
            if (search != -1 && search != cycle.lastIndexOf(n))  //if the value is found more than once in the list
                cycle = cycle.subList(search + 1, cycle.size());  //remove irrelevant values before it since we are only interested in the cycle
                
            cycle.add(n);
            
            if (prevCycle != null) //if it aint null it would always have a value
                prevCycle.add(prevCycle.remove(0)); //rotate cycle for checking
                
            if (cycle.equals(prevCycle))  //if what we did is equivalent to rotating the list, we found it
                repeat = true;
                
            prevCycle = new ArrayList<>(cycle);  //reset prevCycle
        }
        
        return cycle.size() / 2;
    }
}