Problem

Given an unsorted array of size n, find its mean and median.

Definitions

  • Mean: The mean (average) of an array is calculated by summing all the elements and then dividing by the number of elements.
  • Median: The median of an array is the middle element if the number of elements is odd, or the average of the two middle elements if the number of elements is even. The array needs to be sorted to find the median.

Examples

Example 1:

Input: arr = [3, 1, 9, 4, 7]

Output:
Mean: 4.8
Median: 4

Solution

Method 1 - Simple Math

Here is the approach:

  1. Mean Calculation:
    • Sum all the elements in the array.
    • Divide the sum by the number of elements.
  2. Median Calculation:
    • Sort the array.
    • If the number of elements n is odd, the median is the middle element.
    • If the number of elements n is even, the median is the average of the two middle elements.

Code

Java
public class Solution {

    public static double findMean(int[] arr) {
        int sum = 0;
        for (int num : arr) {
            sum += num;
        }
        return (double) sum / arr.length;
    }

    public static double findMedian(int[] arr) {
        Arrays.sort(arr);
        int n = arr.length;
        if (n % 2 == 0) {
            return (arr[n / 2 - 1] + arr[n / 2]) / 2.0;
        } else {
            return arr[n / 2];
        }
    }

    public static void main(String[] args) {
        int[] arr = {3, 1, 9, 4, 7};
        
        double mean = findMean(arr);
        double median = findMedian(arr);
        
        System.out.println("Mean: " + mean);
        System.out.println("Median: " + median);  // Expected output: Mean: 4.8, Median: 4
    }
}
Python
class Solution:
    def find_mean(self, arr: List[int]) -> float:
        return sum(arr) / len(arr)

    def find_median(self, arr: List[int]) -> float:
        arr.sort()
        n = len(arr)
        if n % 2 == 0:
            return (arr[n // 2 - 1] + arr[n // 2]) / 2.0
        else:
            return arr[n // 2]

# Example usage
sol = Solution()
arr = [3, 1, 9, 4, 7]

mean = sol.find_mean(arr)
median = sol.find_median(arr)

print("Mean:", mean)       # Expected output: Mean: 4.8
print("Median:", median)   # Expected output: Median: 4

Complexity

  • ⏰ Time complexity: O(n log n)
    • Calculating the mean is O(n), where n is the number of elements.
    • Calculating the median involves sorting the array, which is O(n log n).
  • 🧺 Space complexity: O(1)