Codepath

Calculating Conservation Statistics

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q
    • What is the desired outcome?
    • To return the number of distinct averages calculated by removing the minimum and maximum populations repeatedly.
    • What input is provided?
    • A 0-indexed integer array species_populations.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Sort the population list, then repeatedly remove the minimum and maximum values, calculate their average, and store it in a set.

1) Sort `species_populations`.
2) Initialize a set `averages` to store distinct averages.
3) While the population list is not empty:
   - Remove the minimum and maximum populations.
   - Calculate their average and add it to the set.
4) Return the size of the set.

⚠️ Common Mistakes

  • Not handling the removal of elements from both ends of the list properly.

I-mplement

def distinct_averages(species_populations):
    # Sort the populations to easily find the min and max
    species_populations.sort()
    
    # Initialize a set to store distinct averages
    averages = set()
    
    while species_populations:
        # Remove the min and max populations
        min_pop = species_populations.pop(0)
        max_pop = species_populations.pop(-1)
        
        # Calculate the average
        average = (min_pop + max_pop) / 2
        
        # Add the average to the set
        averages.add(average)
    
    # Return the number of distinct averages
    return len(averages)
Fork me on GitHub