HackerRank Counting Sort 1 Problem Solution
In this post, we will solve HackerRank Counting Sort 1 Problem Solution.
Comparison Sorting
Quicksort usually has a running time of n x log(n), but is there an algorithm that can sort even faster? In general, this is not possible. Most sorting algorithms are comparison sorts, i.e. they sort a list just by comparing the elements to one another. A comparison sort algorithm cannot beat n x log(n) (worst-case) running time, since n x log(n) represents the minimum number of comparisons needed to know where to place each element. For more details, you can see these notes (PDF).
Alternative Sorting
Another sorting method, the counting sort, does not require comparison. Instead, you create an integer array whose index range covers the entire range of values in your array to sort. Each time a value occurs in the original array, you increment the counter at that index. At the end, run through your counting array, printing the value of each non-zero valued index that number of times.
Example
arr = [1, 1, 3, 2, 1]
All of the values are in the range [0…3], so create an array of zeros, result = [0, 0, 0, 0].
The results of each iteration follow:
i arr[i] result 0 1 [0, 1, 0, 0] 1 1 [0, 2, 0, 0] 2 3 [0, 2, 0, 1] 3 2 [0, 2, 1, 1] 4 1 [0, 3, 1, 1]
The frequency array is [0, 3, 1, 1]. These values can be used to create the sorted array as well: sorted [1, 1, 1, 2, 3].
Note
For this exercise, always return a frequency array with 100 elements. The example above
shows only the first 4 elements, the remainder being zeros.
Challenge
Given a list of integers, count and return the number of times each value appears as an array of integers.
Function Description
Complete the countingSort function in the editor below.
countingSort has the following parameter(s):
- arr[n]: an array of integers
Returns
- int[100]: a frequency array
Input Format
The first line contains an integer n, the number of items in arr.
Each of the next n lines contains an integer arr[i] where 0 ≤ i<n.
Sample Input
100 63 25 73 1 98 73 56 84 86 57 16 83 8 25 81 56 9 53 98 67 99 12 83 89 80 91 39 86 76 85 74 39 25 90 59 10 94 32 44 3 89 30 27 79 46 96 27 32 18 21 92 69 81 40 40 34 68 78 24 87 42 69 23 41 78 22 6 90 99 89 50 30 20 1 43 3 70 95 33 46 44 9 69 48 33 60 65 16 82 67 61 32 21 79 75 75 13 87 70 33
Sample Output
0 2 0 2 0 0 1 0 1 2 1 0 1 1 0 0 2 0 1 0 1 2 1 1 1 3 0 2 0 0 2 0 3 3 1 0 0 0 0 2 2 1 1 1 2 0 2 0 1 0 1 0 0 1 0 0 2 1 0 1 1 1 0 1 0 1 0 2 1 3 2 0 0 2 1 2 1 0 2 2 1 2 1 2 1 1 2 2 0 3 2 1 1 0 1 1 1 0 2 2
Explanation
Each of the resulting values result[i] represents the number of times i appeared in arr.
Counting Sort 1 C Solution
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int size;
scanf("%d", &size);
int result[size];
int i;
memset(result, 0, sizeof(int)* size);
for(i = 0; i < size ; i++){
int number;
scanf("%d", &number);
result[number]++;
}
for(i = 0; i < 100; i++){
printf("%d ", result[i]);
}
return 0;
}
Counting Sort 1 C++ Solution
#include <bits/stdc++.h>
#define ll long long
#define F first
#define S second
#define INF 111111
#define N 5001
#define pi 3.14159265359
using namespace std;
int a[111];
int main() {
int n;
cin >> n;
for(int i = 0; i < n; i ++) {
int x;
cin >> x;
a[x] ++;
}
for(int i = 0; i < 100; i++) cout<<a[i]<<" ";
}
Counting Sort 1 C Sharp Solution
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
class Solution {
static void Main(String[] args) {
int[] res = new int[100];
int n = int.Parse(Console.ReadLine());
string[] parts = Console.ReadLine().Split(' ');
for (int id = 0; id < n; id++)
{
int i = int.Parse(parts[id]);
res[i] = res[i] + 1;
}
for (int i = 0; i < 100; i++) {
if (i > 0) {
Console.Write(" ");
}
Console.Write(res[i]);
}
}
}
Counting Sort 1 Java Solution
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'countingSort' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts INTEGER_ARRAY arr as parameter.
*/
public static List<Integer> countingSort(List<Integer> arr) {
Integer[] frequencyArray = new Integer[100];
Arrays.fill(frequencyArray, 0);
for (Integer i : arr) {
frequencyArray[i]++;
}
return Arrays.asList(frequencyArray);
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList());
List<Integer> result = Result.countingSort(arr);
bufferedWriter.write(
result.stream()
.map(Object::toString)
.collect(joining(" "))
+ "\n"
);
bufferedReader.close();
bufferedWriter.close();
}
}
Counting Sort 1 JavaScirpt Solution
function processData(input) {
var input = input.split("\n");
var arr = input[1].split(" ");
var bin = count(arr);
console.log(bin.join(" "));
};
function count (arr){
var bin = [];
arr.forEach(function (item){
var item = +item
bin[item] = bin[item] + 1 || 1;
});
for (var i=0; i < bin.length-1; i++){
bin[i] = bin[i]||'0' ;
}
return bin;
};
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
Counting Sort 1 Python Solution
n = int(input())
ar = [int(i) for i in str(input()).split()]
freq = [0]*100
for i in ar:
freq[i] += 1
print(' '.join([str(e) for e in freq]))
Other Solutions