2465. Number of Distinct Averages

Explanation

To solve this problem, we can iterate through all possible pairs of numbers in the array, calculate their average, and store the distinct averages in a set. Once we have processed all pairs, the size of the set will give us the number of distinct averages.

  1. We start by initializing a set to store the distinct averages.
  2. We iterate through all pairs of numbers in the array (using two nested loops).
  3. For each pair, we calculate the average and add it to the set.
  4. Finally, we return the size of the set as the number of distinct averages.

Time Complexity: O(n^2) where n is the number of elements in the input array. Space Complexity: O(n) to store the distinct averages.

class Solution {
    public int numberOfDistinctAverages(int[] nums) {
        Set<Double> distinctAverages = new HashSet<>();
        
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                double average = (nums[i] + nums[j]) / 2.0;
                distinctAverages.add(average);
            }
        }
        
        return distinctAverages.size();
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.