Leetcode 2455: Average Value of Even Numbers That Are Divisible by Three

grid47
grid47
Exploring patterns and algorithms
Mar 6, 2024 5 min read

You are given an array of positive integers ’nums’. Your task is to calculate the average value of all even numbers in the array that are also divisible by 3. The average should be rounded down to the nearest integer.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array 'nums' containing positive integers.
Example: nums = [2, 3, 6, 9, 12, 18]
Constraints:
• 1 <= nums.length <= 1000
• 1 <= nums[i] <= 1000
Output: Return the average of all even integers in 'nums' that are divisible by 3. If no such number exists, return 0.
Example: Output: 9
Constraints:
• Return 0 if no valid even numbers divisible by 3 are found.
Goal: To calculate the average of even integers divisible by 3.
Steps:
• 1. Loop through each element in 'nums'.
• 2. Check if the element is even and divisible by 3.
• 3. Keep a running sum of the valid numbers and count how many there are.
• 4. If there are valid numbers, return the sum divided by the count, rounded down. If not, return 0.
Goal: Ensure the solution handles the given input size and constraints efficiently.
Steps:
• The input size can be up to 1000 elements, so the solution should run in linear time.
• The integers in 'nums' can be as large as 1000, so simple modulus operations should be sufficient.
Assumptions:
• The array 'nums' will always contain at least one positive integer.
Input: nums = [2, 3, 6, 9, 12, 18]
Explanation: From the given array, the even numbers divisible by 3 are [6, 12, 18]. The sum of these numbers is 36, and their count is 3. Therefore, the average is 36 / 3 = 12.

Input: nums = [1, 2, 4, 7, 10]
Explanation: There are no even numbers divisible by 3, so the result is 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus