Counting Sort 2

Sort by

recency

|

396 Discussions

|

  • + 0 comments
    def countingSort(arr):
        # Write your code here
        
        new_arr = [0] * 100
        
        for i in arr:
            new_arr[i] += 1
        sorted_arr = []  
        for i in range(len(new_arr)):
            for j in range(new_arr[i]):
                sorted_arr.append(i)
                
        return sorted_arr
    
  • + 0 comments

    NodeJS

    function countingSort(arr) {
        let count = new Array(100).fill(0);
        let result=[];
        
        for(let i=0;i<arr.length;i++) count[arr[i]]++;
        for(let i=0;i<100;i++) {
            while(count[i]>0){
                result.push(i)
                count[i]--;
            }
        }
        return result
        
    }
    
  • + 0 comments

    Here is problem solution in python java c++ c and Javascript - https://programmingoneonone.com/hackerrank-counting-sort-2-problem-solution.html

  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/TPW8IGrTI8A

    vector<int> countingSort(vector<int> arr) {
        vector<int> result, count(100, 0);
        for(int i = 0; i < arr.size(); i++) count[arr[i]]++;
        for(int i = 0; i < 100; i++) result.resize(result.size() + count[i], i);
        return result;
    }
    
  • + 0 comments

    My Java solution with o(n) time complexity and o(n) space complexity:

    public static List<Integer> countingSort(List<Integer> arr) {
            int[] freqArr = new int[100];
            arr.forEach(num -> freqArr[num]++);
    
            return IntStream.range(0, 100)
                .boxed()
                .flatMap(i -> Collections.nCopies(freqArr[i], i).stream())
                .collect(Collectors.toList());
        }