Mean of an Array

97.8k
0

Problem Statement

Given a non-empty integer array nums, return the arithmetic mean of all its elements.

Example 1

Input: nums = [2, 4, 6, 8]

Output: 5

Explanation: Sum = 2 + 4 + 6 + 8 = 20, and total elements = 4. So, mean = 20 / 4 = 5.

Example 2

Input: nums = [5, -2, 10, 3]

Output: 4

Explanation: Sum = 5 + (-2) + 10 + 3 = 16, and total elements = 4. So, mean = 16 / 4 = 4.

Approach

Maintain a running sum while traversing the array.

After every element has been added, divide the total sum by the number of elements. The division must use a floating-point value so that any decimal part of the mean is preserved.

Algorithm

  • Store the number of elements in n, since it will be needed to divide the total sum and calculate the mean.

  • Initialize sum with 0, where it keeps the running total of the elements processed so far.

  • Traverse nums once and add each element to sum, ensuring every value contributes exactly once to the total.

  • Divide sum by n using floating-point division so that the fractional part of the mean is not lost.

  • Return the calculated mean after all elements have been included.

Dry Run

Mean of Array Elements Dry Run.png

Mean of Array Elements Dry Run.png

Solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Calculates the arithmetic mean using the total sum and array size.
double findMean(const vector<int>& nums) {
// This defensive check prevents division by zero for empty input.
if (nums.empty()) {
return 0.0;
}
long long sum = 0;
// Add every element once to calculate the complete total.
for (int value : nums) {
sum += value;
}
// Convert sum to double so the fractional part is preserved.
return (double) sum / nums.size();
}
};
int main() {
vector<int> nums = {1, 2, 3, 4};
Solution solution;
cout << fixed << setprecision(2);
cout << "Mean: " << solution.findMean(nums) << endl;
return 0;
}

Complexity Analysis

Time Complexity: O(N), where N represents the number of elements in the array. Every element is visited exactly once.

Space Complexity: O(1), because only n, sum, and the calculated mean require extra storage.

Interview follow-up Questions

The mean may contain a fractional part. Floating-point division preserves this part, while integer division may discard it.

Arrays

Read Similar Blogs

Comments0