Counting Sort 1

Sort by

recency

|

690 Discussions

|

  • + 0 comments

    why its not working for 5th test case def countingSort(arr): arr.sort() d=arr[-1] l=[] for i in range(d+1): count=0 for j in arr: if i==j: count+=1 l.append(count) return l

  • + 0 comments

    C#

    public static List<int> countingSort(List<int> arr)
        {
            var res = new int[100];      
            
            foreach (var item in arr) {
                res[item] += 1;
            }
            
            return res.ToList();
        }
    
  • + 0 comments

    mine python solution

    def CountingSort(arr):
        lps = [0]*(max(arr)+1)
        for i in arr:
            lps[i] += 1
        return lps
    

    correct solution according to hacker rank

    def CountingSort(arr):
        lps = [0]*(100)
        for i in arr:
            lps[i] += 1
        return lps
    
  • + 0 comments

    My Java 8 Solution:

    public static List<Integer> countingSort(List<Integer> arr) {
            List<Integer> result = new ArrayList<>(Collections.nCopies(100, 0));
            
            for (int number : arr) {
                result.set(number, result.get(number) + 1);
            }
            
            return result;
        }
    
  • + 1 comment

    A couple Python solutions:

    Fun one liner:

    def countingSort(arr):
        return [arr.count(i) for i in range(100)]
    

    Not very optimal, O(n^2) time complexity

    Better but more verbose solution for O(n) time complexity:

    def countingSort(arr):
        counts = [0 for i in range(100)]
        for n in arr:
            counts[n] += 1
        return [counts[i] for i in range(100)]