In this HackerRank Counting Sort 1 problem, you have given a list of integers, count and return the number of times each value appears as an array of integers.
Problem description :
Given a list of integers, count and return the number of times each value appears as an array of integers.
Input = [1, 1, 3, 2, 1]
Output = [0, 3, 1, 1]
In input, we have three occurrence of 1, one occurrence of 2 and one occurrence of 3. So in output put 3 at first index, 1 at second index and 1 at third index.
Input = [2, 2, 1, 6, 5]
Output = [0, 1, 2, 0, 0, 1, 1]
In this problem, we does not have to write entire code of counting sort. we need only first step of counting sort algorithm.
Counting Sort 1 Hacker Rank Solution
Problem solution in C++ programming:
vector<int> countingSort(vector<int> arr) { int max = *max_element(arr.begin(),arr.end()); vector<int> result(max+1,0); for(const auto& i:arr) result[i]++; return vector<int>(result.begin(), result.begin()+100); }
Problem solution in Python programming:
def countingSort(arr): # Write your code here ct=[0 for x in range(100)] for i in arr: ct[i] += 1 return ct
Problem solution in JavaScript programming:
function countingSort(arr) { const freq = Array(100).fill(0); for (let elm of arr) { freq[elm] += 1 } return freq; }
Problem solution in Java programming:
List<Integer> response = new ArrayList<>(); for (int i = 0; i < 100; i++) { response.add(0); } for (Integer i : arr) { response.set(i, response.get(i) + 1); } return response;
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.