public static String rearrangeString(String input, int distance) {
        Map<Character, Integer>  frequencyCounter = new HashMap<>();
        PriorityQueue<Pair> heap = new PriorityQueue<Pair>(input.length(), new Comparator<Pair>(){

            @Override
            public int compare(Pair o1, Pair o2) {
                return -1 *(o1.frequency.compareTo(o2.frequency));
            }
        });

        char[] inp = input.toCharArray();
        //frequency counting
        for( int i=0; i< inp.length; i++) {
            if(frequencyCounter.containsKey(inp[i])){
                frequencyCounter.put(inp[i], frequencyCounter.get(inp[i]) +1);
            } else {
                frequencyCounter.put(inp[i], 1);
            }
            //nulling the array
            inp[i] = '\0';
        }

        //maxHeapify the entries
        for(Map.Entry<Character,Integer> entry : frequencyCounter.entrySet()){
            heap.add(new Pair(entry.getKey(),entry.getValue()));
        }

        //iterate on heap in MaxHeap order
        while(!heap.isEmpty()){
            int i = 0;
            //find the first '\0' charcter
            for(; i<inp.length; i++){
                if(inp[i] =='\0'){
                    break;
                }
            }
            Pair p = heap.remove();
            // add the elements starting from that charcter
            for( int j = 0; j< p.frequency; j++){
                inp[i +(j*distance)] = p.a;
            }

        }

        return new String(inp);

    }