Leetcode 2455. Average Value of Even Numbers That Are Divisible by Three
Problem Statement
Given an integer array nums
of positive integers, calculate and return the average of all even numbers that are divisible by 3. If there are no such numbers, return 0.
Clarifying Questions
- Input constraints: What is the maximum length of the input array?
- The array can have up to 10^4 integers.
- Input values: Are all input values guaranteed to be positive integers?
- Yes, all values will be positive integers.
- Return type: Should the function return an integer or a float for the average value?
- The function should return an integer. We’ll take the floor value of the average if it’s not a whole number.
- Edge cases: What should be returned if there are no even numbers divisible by 3?
- If there are no such numbers, the function should return 0.
Strategy
- Iteration: Iterate through the array and check each number.
- Conditions: Determine if a number is both even and divisible by 3.
- Accumulation: Accumulate the sum of these qualifying numbers and count them.
- Calculation: Calculate the average based on the sum and count.
- Return: Return the integer part of the calculated average or 0 if no qualifying numbers are found.
Code
public class Solution {
public int averageValue(int[] nums) {
int sum = 0;
int count = 0;
for (int num : nums) {
if (num % 2 == 0 && num % 3 == 0) {
sum += num;
count++;
}
}
// If no even numbers that are divisible by 3 are found
if (count == 0) {
return 0;
}
// Calculate and return the average (floor division)
return sum / count;
}
}
Time Complexity
- O(n): The algorithm iterates through the array once, where
n
is the length of the input array nums
.
- Space Complexity: O(1) since we use a constant amount of extra space regardless of the input size.
This approach ensures that we efficiently compute the desired average with a guaranteed linear time complexity.
Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI
-
Got blindsided by a question you didn’t expect?
-
Spend too much time studying?
-
Or simply don’t have the time to go over all 3000 questions?