You are given a 0-indexed integer array nums
of even length. As long as nums
is not empty, you must repetitively:
nums
.nums
.Your task is to return the number of distinct averages computed.
-10^6
to 10^6
.Now, we’ll proceed with implementing the solution.
Sort the Array: First, sort the given array to easily find the minimum and maximum values.
Two Pointer Technique: Use two pointers, one starting from the beginning (left) and one from the end (right) of the sorted array.
Compute Averages: Iteratively compute the average of the values at the two pointers, store the average in a set (to keep track of distinct averages), and move the pointers towards each other.
Remove Values: After computing the average, increment the left
pointer and decrement the right
pointer to remove both the minimum and maximum from the array implicitly.
Continue Until the Pointers Meet: Repeat steps 3-4 until the pointers meet.
Return the Size of the Set: Finally, return the size of the set containing distinct averages.
def distinct_averages(nums):
# Sort the array to facilitate the two-pointer technique
nums.sort()
distinct_avg_set = set()
left, right = 0, len(nums) - 1
# Loop until pointers meet
while left < right:
# Compute the average of nums[left] and nums[right]
avg = (nums[left] + nums[right]) / 2
# Add it to the set of distinct averages
distinct_avg_set.add(avg)
# Move pointers
left += 1
right -= 1
# The number of distinct averages is the size of the set
return len(distinct_avg_set)
# Example usage:
nums = [4,1,4,0,3,5]
print(distinct_averages(nums)) # Output should be the number of distinct averages
Overall, the time complexity of this solution is O(n \log n) due to the sorting step.
The space complexity is O(1) for the two-pointer technique plus O(D) for the set storing distinct averages where D is the number of distinct averages (in the worst case D could be up to (n/2)).
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?