easyArrays

Find the Average Presence Solution

Problem Statement

Given an array of integers, calculate the average of all elements. Determine if that average value exists within the original array. Note: For this problem, if the average is not an integer, it is considered not present in the array.

Examples

Example 1:
Input:[1, 2, 3, 4, 5]
Output:true
Explanation: The sum is 1+2+3+4+5 = 15. The average is 15/5 = 3. 3 is present in the array.
Example 2:
Input:[10, 20]
Output:false
Explanation: The sum is 10+20 = 30. The average is 30/2 = 15. 15 is not present in the array.

Constraints

  • Array length will be between 1 and 1000.
  • Elements will be integers between -1000 and 1000.
Time: O(N) Space: O(1)
The optimal approach calculates the sum of all elements in a single pass. We verify if the sum is perfectly divisible by the array's length; if not, we immediately return false. If it is divisible, we calculate the integer average and perform a single linear scan (or use a hash set for O(1) lookups) to check if the average exists in the array.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

class Solution: def findAveragePresence(self, nums: list[int]) -> bool: if not nums: return False total_sum = sum(nums) n = len(nums) if total_sum % n != 0: return False avg = total_sum // n return avg in nums