2 minute read

The Full Counting Sort (Hacker Rank)

In this challenge you need to print the data that accompanies each integer in a list. In addition, if two strings have the same integers, you need to print the strings in their original order. Hence, your sorting algorithm should be stable, i.e. the original order should be maintained for equal elements.

Insertion Sort and the simple version of Quicksort were stable, but the faster in-place version of Quicksort was not (since it scrambled around elements while sorting).

In cases where you care about the original order, it is important to use a stable sorting algorithm. In this challenge, you will use counting sort to sort a list while keeping the order of the strings (with the accompanying integer) preserved.

Challenge In the previous challenge, you created a “helper array” that contains information about the starting position of each element in a sorted array. Can you use this array to help you create a sorted array of the original list?

Hint: You can go through the original array to access the strings. You can then use your helper array to help determine where to place those strings in the sorted array. Be careful about being one off.

Details and a Twist You will be given a list that contains both integers and strings. Can you print the strings in order of their accompanying integers? If the integers for two strings are equal, ensure that they are print in the order they appeared in the original list.

The Twist - Your clients just called with an update. They don’t want you to print the first half of the original array. Instead, they want you to print a dash for any element from the first half.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

   public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        StringBuilder[] result = new StringBuilder[n];
        int max = 0;
        for(int i = 0; i < n; i++){
            int num = in.nextInt();
            String str = in.next();
            if(num > max){
                max = num;
            }
            str = (i < n/2)? "-" + " " : str + " ";
            if(result[num] == null){
                result[num] = new StringBuilder();
            }
            result[num].append(str);
        }
       for(int j = 0; j < max+1; j++){
           if(result[j] != null){
               System.out.print(result[j]);
           }
       }
    }
}
행운의 77문제 프로젝트
  행운의 77문제 프로젝트는 한 달동안 알고리즘 문제 77개를 푸는 프로젝트입니다.