The Full Counting Sort HackerRank Solution in C, C++, Java, Python

Use the counting sort to order a list of strings associated with integers. If two strings are associated with the same integer, they must be printed in their original order, i.e. your sorting algorithm should be stable. There is one other twist: strings in the first half of the array are to be replaced with the character – (dash, ascii 45 decimal).Insertion Sort and the simple version of Quicksort are stable, but the faster in-place version of Quicksort is not since it scrambles around elements while sorting. Design your counting sort to be stable.

Example

The first two strings are replaced with ‘-‘. Since the maximum associated integer is , set up a helper array with at least two empty arrays as elements. The following shows the insertions into an array of three empty arrays.

i string converted list

0 [[],[],[]]

1  a  - [[-],[],[]]

2 b - [[-],[-],[]]

3 c [[-,c],[-],[]]

4 d [[-,c],[-,d],[]]

 

The result is then printed:  .

Function Description

Complete the countSort function in the editor below. It should construct and print the sorted strings.

countSort has the following parameter(s):

  • string arr[n][2]: each arr[i] is comprised of two strings, x and s

Returns

– Print the finished array with each element separated by a single space.

Note: The first element of each arr[i], x, must be cast as an integer to perform the sort.

Input Format

The first line contains n, the number of integer/string pairs in the array arr.

Each of the next n contains x[i] and s[i], the integers (as strings) with their associated strings.

Output Format

Print the strings in their correct order, space-separated on one line.

Sample Input

20

0 ab

6 cd

0 ef

6 gh

4 ij

0 ab

6 cd

0 ef

6 gh

0 ij

4 that

3 be

0 to

1 be

5 question

1 or

2 not

4 is

2 to

4 the

 

Sample Output

- - - - - to be or not to be - that is the question - - - -

 

Explanation

The correct order is shown below. In the array at the bottom, strings from the first half of the original array were replaced with dashes.

0 ab

0 ef

0 ab

0 ef

0 ij

0 to

1 be

1 or

2 not

2 to

3 be

4 ij

4 that

4 is

4 the

5 question

6 cd

6 gh

6 cd

6 gh

 

sorted = [['-', '-', '-', '-', '-', 'to'], ['be', 'or'], ['not', 'to'], ['be'], ['-', 'that', 'is', 'the'], ['question'], ['-', '-', '-', '-'], [], [], [], []]

The Full Counting Sort HackerRank Solution in C

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int* hist[100];
int size[100];
int pos[100];

int main() {
    int BUF_SZ = 256;
    int N, v, i, j;
    scanf("%d", &N);
    fprintf(stderr, "%d elements\n", N);
    char *data[N];
    for (i = 0; i < N; ++i) {
        if (i < N/2) {
            data[i] = (char*)malloc(BUF_SZ*sizeof(char));
        }
        scanf("%d %s", &v, data[i<N/2?i:i-N/2]);
        if (hist[v] == NULL) {
            size[v] = 2*N/100 + 1;
            hist[v] = (int*)malloc(size[v]*sizeof(int));
        } else if (pos[v] >= size[v]) {
            size[v] *= 2;
            hist[v] = (int*)realloc(hist[v], size[v]*sizeof(int));
        }
        (hist[v])[pos[v]++] = i;
    }
    for (i = 0; i < 100; ++i) {
        fprintf(stderr, "Printing %d\n", i);
        for (j = 0; j < pos[i]; ++j) {
            if ((hist[i])[j] < N/2) {
                printf("- ");
            } else {
                printf("%s ", data[(hist[i])[j]-N/2]);
                free(data[(hist[i])[j]-N/2]);
            }
        }
        if (hist[i] != NULL) {
            free(hist[i]);
            hist[i] = NULL;
        }
    }
    return 0;
}

 

The Full Counting Sort HackerRank Solution in C++

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include<string>
#include<list>
using namespace std;


vector<string> a[100];
char str[100007];
int n,i,j,x;

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    
    
    cin>>n;
    for(i=0;i<n/2;i++)
    {
        cin>>x;
        cin>>str;
        a[x].push_back("-");
    
    }
    
    for(;i<n;i++)
    {
        cin>>x;
        cin>>str;
        a[x].push_back(str);
    
    }
    
    for(i=0;i<100;i++)
    {
        x=a[i].size();
        for(j=0;j<x;j++)
            cout<<a[i][j]<<" ";    
    }
    return 0;

}

 

The Full Counting Sort HackerRank Solution in Python

n = int(input())
counts = [0] * 100
helper = [[] for i in xrange(100)]

for i in xrange(n):
    arr = raw_input().split()
    num = int(arr[0])
    counts[num] = counts[num] + 1
    helper[num].append((i, arr[1]))
    
for i in xrange(100):
    for j in xrange(counts[i]):
        if helper[i][j][0] < n / 2:
            print "-",
        else:
            print helper[i][j][1],

 

The Full Counting Sort HackerRank Solution in Java

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) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(in.readLine());
        StringBuffer[] map = new StringBuffer[100];
        for(int i = 0; i < 100; i++) {
            map[i] = new StringBuffer();
        }
        for(int i = 0; i < n; i++) {
            StringTokenizer tok = new StringTokenizer(in.readLine());
            int v = Integer.parseInt(tok.nextToken());
            String s = tok.nextToken();
            map[v].append(i < n / 2 ? "-" : s).append(" ");
        }
        for(int i = 0; i < 100; i++) {
            System.out.print(map[i]);
        }
        System.out.println();
    }
}

 

The Full Counting Sort HackerRank Solution in C#

using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
class Solution {
    static void Main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
        int N = int.Parse(Console.ReadLine());
        //string[] split = 
        int[] a = new int[N];
        int[] n = new int[N];
        string[] str = new string[N];
        for(int i = 0; i < N; i++){
            string[] split = Console.ReadLine().Split(' ');
            a[i] = int.Parse(split[0]);
            str[i] = split[1];
            n[a[i]]++;
        }
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < N; i++){
            if(n[i] != 0){
                for(int j = 0; j < N; j++){
                    if(a[j] == i)
                        //Console.Write(string.Format("{1}-{0} ", str[j], j));
                        sb.Append(j < N / 2 ? "- " : str[j] + " ");
                }
            }
        }
        Console.WriteLine(sb.ToString());
        
    }
}

 

Attempt Full Counting Sort HackerRank Challenge

Link – https://www.hackerrank.com/challenges/countingsort4/

Next HackerRank Challenge Solution 

Link – https://exploringbits.com/beautiful-binary-string-hackerrank-solution/

Leave a Comment