Find the Average of an Array
Solve this ProblemEasy5 min
Topics
BasicsArrays
Companies
TCSInfosysWipro
Given an array
nums of non-negative integers, return the average of its elements as text with two decimal places.
The averageAverage (Mean)The sum of the values divided by how many values there are. combines two array basics — a running sum and the array's length — with a lesson from earlier: the final division must be done in floating point, or the fractional part is lost. A wider type for the sum is a good habit too, since totals grow much faster than individual values.
Test Case 1:
Input:nums = [4, 9, 2, 5]
Output:"5.00"
Explanation:The sum is 20 and there are 4 values: 20 / 4 = 5.
Test Case 2:
Input:nums = [1, 2]
Output:"1.50"
Explanation:Dividing as decimals keeps the half.
Constraints
- ◆
1 ≤ nums.length ≤ 1000 - ◆
0 ≤ nums[i] ≤ 1000000
Try the Dry Run
Approach & Solutions
Sum in a Loop, Then DivideGood
Add all elements with a running total, then divide by the number of elements. The division must be done with decimals — cast the total to double first — otherwise integer division would drop the fraction. Format the result with two decimal places.
Time
O(n)Space
O(1)Java
class Solution {
public String averageOfArray(int[] nums) {
long total = 0;
for (int value : nums) {
total += value;
}
double average = (double) total / nums.length;
return String.format("%.2f", average);
}
}Built-in AverageOptimal
Let the library do it: Arrays.stream(nums).average() in Java, sum(nums) / len(nums) in Python, accumulate(...) divided by the size in C++, and reduce in JavaScript. C has no built-in, so it keeps the loop. The output is still formatted to two decimals.
Time
O(n)Space
O(1)Java
class Solution {
public String averageOfArray(int[] nums) {
double average = Arrays.stream(nums).average().getAsDouble();
return String.format("%.2f", average);
}
}