Skip to main content

Math Basics

Find the Mean/Median/Mode of the Given Array Solution In C++/Java/Python/JS

Description

Statistical measures help us understand data distribution and central tendency. When analyzing data, we often need to find representative values that summarize the entire dataset.

The three most common statistical measures are:

  1. Mean: The arithmetic average of all values in the array.
  2. Median: The middle value when the array is arranged in order.
  3. Mode: The most frequently occurring value(s) in the array.

Each measure provides different insights:

  • Mean represents the average value and works best with symmetrically distributed data.
  • Median represents the middle value and is useful for skewed data with outliers.
  • Mode represents the most common value and is particularly useful for categorical data.

Example

Let's consider an array [4, 7, 9, 2, 8, 5, 1, 6, 4] and calculate all three measures:
Mean :

  • Sum of all elements: 4 + 7 + 9 + 2 + 8 + 5 + 1 + 6 + 4 = 46
  • Number of elements: 9
  • Mean = 46 ÷ 9 = 5.11

Median :

  • Sorted array: [1, 2, 4, 4, 5, 6, 7, 8, 9]
  • Middle position: 5th element (in a 9-element array)
  • Median = 5

Mode :

  • Frequency count: 4 appears twice, all other values appear once
  • Mode = 4 (most frequent value)

Mean Approach

Step 1: Initialize a variable sum to 0.

Step 2: Iterate through each element in the array and add it to sum.

Step 3: Divide sum by the number of elements in the array.

Step 4: Iterate through each element in the array and add it to sum.

Median Approach

Step 1: Sort the array in ascending order.

Step 2: If the array has an odd number of elements:

  • Return the middle element.

Step 3: If the array has an even number of elements:

  • Return the average of the two middle elements.

Mode Approach

Step 1: Create a frequency map to count occurrences of each value.

Step 2: Find the maximum frequency.

Step 3: Return all values that appear with the maximum frequency.

Step 4: If all values appear with equal frequency, there is no mode.

Code for All Languages
C++
// Language: C++  

#include <iostream>  
#include <vector>  
#include <algorithm>  
#include <unordered_map>  

using namespace std;  

class Solution {  
public:  
    // Step 1: Function to calculate mean of an array  
    double findMean(const vector<int>& arr) {  
        // Initialize sum to zero  
        double sum = 0;  
        
        // Sum all elements in the array  
        for (int num : arr) {  
            sum += num;  
        }  
        
        // Return the average (sum divided by count)  
        return arr.empty() ? 0 : sum / arr.size();  
    }  

    // Step 2: Function to calculate median of an array  
    double findMedian(vector<int> arr) {  
        // Check if array is empty  
        if (arr.empty()) {  
            return 0;  
        }  
        
        // Sort the array in ascending order  
        sort(arr.begin(), arr.end());  
        
        // Get the size of the array  
        int n = arr.size();  
        
        // If array has odd number of elements  
        if (n % 2 != 0) {  
            return arr[n / 2];  
        }  
        
        // If array has even number of elements  
        return (arr[(n - 1) / 2] + arr[n / 2]) / 2.0;  
    }  

    // Step 3: Function to calculate mode of an array  
    vector<int> findMode(const vector<int>& arr) {  
        // Check if array is empty  
        if (arr.empty()) {  
            return {};  
        }  
        
        // Create a frequency map  
        unordered_map<int, int> frequencyMap;  
        int maxFrequency = 0;  
        
        // Count frequency of each element  
        for (int num : arr) {  
            frequencyMap[num]++;  
            maxFrequency = max(maxFrequency, frequencyMap[num]);  
        }  
        
        // If all elements occur once, there is no mode  
        if (maxFrequency == 1) {  
            return {};  
        }  
        
        // Create a vector of modes  
        vector<int> modes;  
        for (const auto& pair : frequencyMap) {  
            if (pair.second == maxFrequency) {  
                modes.push_back(pair.first);  
            }  
        }  
        
        return modes;  
    }  
};  

// Step 4: Driver code to demonstrate usage  
int main() {  
    // Define the array  
    vector<int> arr;  
    int n;  
    
    // Take input from the user 
    cin >> n;  
    
    for (int i = 0; i < n; i++) {  
        int num;  
        cin >> num;  
        arr.push_back(num);  
    }  
    
    // Create an instance of Solution class  
    Solution sol;  
    
    // Calculate and display mean  
    cout << "Mean: " << sol.findMean(arr) << endl;  
    
    // Calculate and display median  
    cout << "Median: " << sol.findMedian(arr) << endl;  
    
    // Calculate and display mode  
    vector<int> modes = sol.findMode(arr);  
    cout << "Mode(s): ";  
    if (modes.empty()) {  
        cout << "No mode";  
    } else {  
        for (int mode : modes) {  
            cout << mode << " ";  
        }  
    }  
    cout << endl;  
    
    return 0;  
}

Java
// Language: java

import java.util.*;

class Solution {
    // Function to calculate mean
    public double findMean(int[] arr) {
        if (arr.length == 0) return 0;
        double sum = 0;
        for (int num : arr) {
            sum += num;
        }
        return sum / arr.length;
    }

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

    // Function to calculate mode
    public List<Integer> findMode(int[] arr) {
        if (arr.length == 0) return new ArrayList<>();

        Map<Integer, Integer> frequencyMap = new HashMap<>();
        int maxFrequency = 0;

        for (int num : arr) {
            frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
            maxFrequency = Math.max(maxFrequency, frequencyMap.get(num));
        }

        if (maxFrequency == 1) return new ArrayList<>();

        List<Integer> modes = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
            if (entry.getValue() == maxFrequency) {
                modes.add(entry.getKey());
            }
        }
        return modes;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int[] arr = new int[n];

        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt();
        }
        scanner.close();

        Solution sol = new Solution();
        System.out.println("Mean: " + sol.findMean(arr));
        System.out.println("Median: " + sol.findMedian(arr));

        List<Integer> modes = sol.findMode(arr);
        System.out.print("Mode(s): ");
        if (modes.isEmpty()) {
            System.out.println("No mode");
        } else {
            for (int mode : modes) {
                System.out.print(mode + " ");
            }
            System.out.println();
        }
    }
}

Python
# Language: Python  

class Solution:
    # Function to calculate mean
    def find_mean(self, arr):
        return sum(arr) / len(arr) if arr else 0

    # Function to calculate median
    def find_median(self, arr):
        if not arr:
            return 0
        arr.sort()
        n = len(arr)
        mid = n // 2
        return arr[mid] if n % 2 != 0 else (arr[mid - 1] + arr[mid]) / 2.0

    # Function to calculate mode
    def find_mode(self, arr):
        if not arr:
            return []
        
        from collections import Counter
        frequency = Counter(arr)
        max_freq = max(frequency.values())

        if max_freq == 1:
            return []

        return [num for num, freq in frequency.items() if freq == max_freq]

# Driver code
if __name__ == "__main__":
    n = int(input())
    arr = list(map(int, input().split()))

    sol = Solution()
    
    print("Mean:", sol.find_mean(arr))
    print("Median:", sol.find_median(arr))
    
    modes = sol.find_mode(arr)
    print("Mode(s):", " ".join(map(str, modes)) if modes else "No mode")


Javascript
// Language: JavaScript  

class Solution {
    // Function to calculate mean
    findMean(arr) {
        if (arr.length === 0) return 0;
        let sum = arr.reduce((acc, num) => acc + num, 0);
        return sum / arr.length;
    }

    // Function to calculate median
    findMedian(arr) {
        if (arr.length === 0) return 0;
        arr.sort((a, b) => a - b);
        let n = arr.length;
        let mid = Math.floor(n / 2);
        return n % 2 !== 0 ? arr[mid] : (arr[mid - 1] + arr[mid]) / 2.0;
    }

    // Function to calculate mode
    findMode(arr) {
        if (arr.length === 0) return [];
        
        let frequencyMap = new Map();
        let maxFrequency = 0;

        for (let num of arr) {
            frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1);
            maxFrequency = Math.max(maxFrequency, frequencyMap.get(num));
        }

        if (maxFrequency === 1) return [];

        let modes = [];
        for (let [num, freq] of frequencyMap.entries()) {
            if (freq === maxFrequency) {
                modes.push(num);
            }
        }
        return modes;
    }
}

// Driver code
const readline = require("readline");

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("", (n) => {
    rl.question("", (input) => {
        let arr = input.split(" ").map(Number);
        let sol = new Solution();

        console.log("Mean:", sol.findMean(arr));
        console.log("Median:", sol.findMedian(arr));

        let modes = sol.findMode(arr);
        console.log("Mode(s):", modes.length > 0 ? modes.join(" ") : "No mode");

        rl.close();
    });
});

Time and Space Complexity Analysis

Mean:

  • Time Complexity: O(n) - We need to iterate through all n elements once.
  • Space Complexity: O(1) - Only requires a few variables regardless of input size.

Median:

  • Time Complexity: O(n log n) - Dominated by the sorting operation
  • Space Complexity:
    • O(n) for languages that make a copy during sorting
    • O(1) or O(log n) for in-place sorting algorithms

Mode:

  • Time Complexity: O(n) - We need to count frequencies in one pass
  • Space Complexity: O(k) where k is the number of unique elements in the array

Similar Problems

If you're interested in finding the mean, median, and mode of arrays, you might also want to explore these related problems:

This problem requires finding the k closest elements to a given value in an array, which involves sorting and calculating distances (similar to calculations we perform for finding the median).

In this problem, you need to rank teams based on votes they received. This involves frequency counting and sorting, similar to what we do when finding the mode.