Problem statement

https://leetcode.com/problems/statistics-from-a-large-sample/

Solution

Actually, this is a bunch of different problems here. Most difficult is for median: let helper(k) be function, which return k-th number, then we can use it to deal with odd and even cases.

Complexity

It is O(n), where n = 256 is the range of numbers.

Code

class Solution:
    def sampleStats(self, count):
        ans, n = [0] * 5, 256
        for i in range(n):
            if count[i] != 0:
                ans[0] = i
                break
                
        for i in range(n-1, -1, -1):
            if count[i] != 0:
                ans[1] = i
                break
        
        m = sum(count)
        ans[2] = sum(i * count[i] for i in range(n))/m
        ans[4] = count.index(max(count))

        
        def helper(k):
            for i in range(n):
                if k >= count[i]:
                    k -= count[i]
                else:
                    return i
                
        if m % 2 == 1:
            ans[3] = helper(m//2)
        else:
            ans[3] = (helper(m//2 - 1) + helper(m//2))/2
            
        return ans