algoadvance

Given an array of unique integers salary where salary[i] is the salary of the ith employee, return the average salary of employees excluding the minimum and maximum salary.

Example:

Clarifying Questions

  1. Input Size: What is the maximum length of the salary array?
    • Typically, constraints are provided in coding platforms, but for now, we’ll assume it could be any reasonable length fitting within typical system memory.
  2. Uniqueness: Are all salary entries unique?
    • Yes, per the problem statement.
  3. Decimal Precision: Is there a specific requirement for decimal precision of the output?
    • The output should typically be returned in floating point format, so ensuring up to five decimal places precision is a safe approach if not further specified.

Strategy

To solve this problem, we can follow these steps:

  1. Remove the minimum salary from the list.
  2. Remove the maximum salary from the list.
  3. Calculate the average of the remaining salaries.

Here is the algorithm:

  1. Sort the array.
  2. Ignore the first element (minimum) and the last element (maximum).
  3. Calculate the average of the remaining elements.

Time Complexity

The sorting step will dominate the time complexity, which will be O(n log n), where n is the number of elements in the array. Other operations (finding the sum and average) are linear, i.e., O(n).

Code

Here is the implementation of the strategy:

def average(salary):
    # Sort the salary list to find min and max easily
    salary.sort()
    
    # Excluding the first and last element (which are min and max)
    sum_of_salaries = sum(salary[1:-1])
    count_of_salaries = len(salary) - 2
    
    # Calculating average
    return sum_of_salaries / count_of_salaries

# Example test case
salary = [4000, 3000, 1000, 2000]
print(average(salary))  # Output: 2500.0

By following this approach, the code efficiently excludes the minimum and maximum salaries and computes the average of the rest.

Try our interview co-pilot at AlgoAdvance.com