Skip to main content

Number of Distinct Averages - Solution & Explanation

EasyArrayHash TableTwo PointersSorting18 min readAsked at: Amazon
Practice this problem

Problem Statement

You are given a 0-indexed integer array nums of even length.

As long as nums is not empty, you must repetitively:

  • Find the minimum number in nums and remove it.
  • Find the maximum number in nums and remove it.
  • Calculate the average of the two removed numbers.

The average of two numbers a and b is (a + b) / 2.

  • For example, the average of 2 and 3 is (2 + 3) / 2 = 2.5.

Return the number of distinct averages calculated using the above process.

Note that when there is a tie for a minimum or maximum number, any can be removed.

 

Example 1:

Input: nums = [4,1,4,0,3,5]
Output: 2
Explanation:
1. Remove 0 and 5, and the average is (0 + 5) / 2 = 2.5. Now, nums = [4,1,4,3].
2. Remove 1 and 4. The average is (1 + 4) / 2 = 2.5, and nums = [4,3].
3. Remove 3 and 4, and the average is (3 + 4) / 2 = 3.5.
Since there are 2 distinct numbers among 2.5, 2.5, and 3.5, we return 2.

Example 2:

Input: nums = [1,100]
Output: 1
Explanation:
There is only one average to be calculated after removing 1 and 100, so we return 1.

 

Constraints:

  • 2 <= nums.length <= 100
  • nums.length is even.
  • 0 <= nums[i] <= 100

Approach Overview

Problem Overview: You are given an even-length integer array. In each step, remove the smallest and largest numbers, compute their average, and store it. Repeat until the array is empty. The goal is to return how many distinct averages appear during this process.

Approach 1: Using Hash Maps / Hash Set (O(n log n) time, O(n) space)

This approach focuses on tracking unique averages using a hash-based structure. First, sort the array so the smallest and largest values can be accessed easily. Then iterate using two pointers: one at the beginning and one at the end of the array. For every pair, compute the average using (nums[left] + nums[right]) / 2 and insert the result into a hash set. Because sets store only unique values, duplicates are automatically removed. Continue moving the pointers inward until all elements are processed.

The key idea is that the order of removal does not affect the result once the array is sorted. Every step always combines the smallest and largest remaining elements. The hash structure guarantees O(1) average insertion and lookup, so counting distinct averages becomes straightforward. This method works well for general hash table problems where uniqueness needs to be tracked efficiently.

Approach 2: Using Sorting and Two Pointers (O(n log n) time, O(n) space)

Another clean solution relies on sorting and the classic two-pointer technique. After sorting the array, place one pointer at the start and another at the end. Each iteration forms a pair consisting of the minimum and maximum remaining values. Compute their sum or average and store it in a set. Move the left pointer forward and the right pointer backward until they cross.

The sorting step dominates the runtime with O(n log n), while the pairing process itself runs in O(n). This approach highlights a common pattern in two pointers and sorting problems: sort first, then process symmetric elements from both ends. It avoids repeated scanning for minimum or maximum values and keeps the implementation compact.

Recommended for interviews: Interviewers usually expect the sorting + two-pointer solution. It demonstrates recognition of a symmetric pairing pattern and efficient iteration across the array. Mentioning a hash set to track unique averages shows awareness of constant-time lookups. A brute-force idea (repeatedly scanning for min and max) shows baseline understanding, but the sorted two-pointer solution shows stronger algorithmic thinking.

Approach 1: Approach 1: Using Hash Maps

This approach utilizes hash maps (or dictionaries) to store and efficiently query required data. The hash map data structure offers average constant time complexity for insertions and lookups, making it ideal for problems where we need to frequently access or update information.

This C solution implements a simplistic hash table using separate chaining to handle collisions. We define an entry structure that holds a key-value pair and we use an array of entry pointers as our hash table. The 'hashFunction' maps the key to an array index, and 'insert' adds new entries, while 'search' retrieves the value for a given key, or -1 if the key isn't found.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(1) on average for insert and search, O(n) in the worst case due to collisions.
Space Complexity: O(n), where n is the number of elements stored in the hash table.

Try this approach in the editor →

Approach 2: Approach 2: Using Sorting and Binary Search

This approach involves first sorting the data, which allows us to use binary search for efficient lookups. Although this incurs a sorting overhead, it can be effective when dealing with static data where many lookups are needed and few or no updates.

This C solution demonstrates sorting an array using qsort and then performs a binary search. We define a comparison function to allow qsort to order the array. The binarySearch function uses iteration to efficiently find an element, returning its index or -1 if absent.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n log n) for sorting, O(log n) for each search.
Space Complexity: O(1) for in-place sorting.

Try this approach in the editor →

Approach 3: Sorting

The problem requires us to find the minimum and maximum values in the array nums each time, delete them, and then calculate the average of the two deleted numbers. Therefore, we can first sort the array nums, then take the first and last elements of the array each time, calculate their sum, use a hash table or array cnt to record the number of times each sum appears, and finally count the number of different sums.

The time complexity is O(n times log n), and the space complexity is O(n). Here, n is the length of the array nums.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Approach 4: Default Approach

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Approach 1: Using Hash Maps

Time Complexity: O(1) on average for insert and search, O(n) in the worst case due to collisions.
Space Complexity: O(n), where n is the number of elements stored in the hash table.

Approach 2: Using Sorting and Binary Search

Time Complexity: O(n log n) for sorting, O(log n) for each search.
Space Complexity: O(1) for in-place sorting.

Sorting
Default Approach

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Hash Set with Pair TrackingO(n log n)O(n)General solution when you need to track distinct averages efficiently
Sorting + Two PointersO(n log n)O(n)Preferred interview approach when pairing smallest and largest elements

Video Solution

Leetcode | 2465. Number of Distinct Averages | Easy | Java SolutionDeveloper Docs905 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Number of Distinct Averages easy or hard?
Number of Distinct Averages is classified as an Easy problem. The challenge mainly tests understanding of sorting and the two-pointer technique, along with using a set to track unique values.
How to solve Number of Distinct Averages in O(n)?
Achieving strict O(n) time is difficult because identifying smallest and largest elements repeatedly usually requires sorting or priority structures. Most implementations sort the array once and then use two pointers. The resulting complexity is O(n log n), which is considered optimal for this problem.
What is the best approach for Number of Distinct Averages?
The most practical approach is sorting the array and using two pointers from both ends. After sorting, pair the smallest and largest numbers, compute their average, and store it in a hash set to keep only unique values. The sorting step takes O(n log n) time and the pairing step takes O(n), giving an overall complexity of O(n log n) with O(n) extra space.
What data structure is used in Number of Distinct Averages?
A hash set (or hash map variant) is used to store averages and ensure uniqueness. The array is typically sorted first, and then two pointers select the smallest and largest elements at each step. The hash set allows O(1) average-time insertion and membership checks.
What is the time complexity of Number of Distinct Averages?
The optimal solution runs in O(n log n) time because the array must be sorted first. After sorting, pairing elements with two pointers takes O(n). Space complexity is O(n) due to the hash set used to track distinct averages.
Number of Distinct Averages Python or Java solution approach?
Both Python and Java implementations follow the same pattern: sort the array, use two pointers to pair elements, compute the average, and insert it into a set. Python typically uses a built-in set, while Java uses HashSet. The algorithmic complexity remains O(n log n) time and O(n) space.
Is Number of Distinct Averages asked at Google, Amazon, or Meta?
Problems involving pairing extremes, computing averages, and tracking unique results appear frequently in interviews at companies like Amazon, Google, and Meta. While this exact problem may not always appear, the underlying patterns—sorting, two pointers, and hash sets—are common interview topics.

Ready to solve this problem?

Practice Number of Distinct Averages with our built-in code editor and test cases.

Practice on FleetCode