Solving Leetcode Interviews in Seconds with AI: Average Salary Excluding the Minimum and Maximum Salary
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1491" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
You are 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. Answers within 10-5 of the actual answer will be accepted. Example 1: Input: salary = [4000,3000,1000,2000] Output: 2500.00000 Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively. Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500 Example 2: Input: salary = [1000,2000,3000] Output: 2000.00000 Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively. Average salary excluding minimum and maximum salary is (2000) / 1 = 2000 Constraints: 3 <= salary.length <= 100 1000 <= salary[i] <= 106 All the integers of salary are unique.
Explanation
Here's the breakdown of the solution:
- Find Minimum and Maximum: Iterate through the array once to determine the minimum and maximum salary.
- Calculate Sum (excluding min/max): Simultaneously during the min/max finding, compute the sum of all salaries. Then, subtract the min and max from the total sum.
Calculate Average: Divide the adjusted sum by the number of employees minus 2 (since we excluded the min and max).
Runtime Complexity: O(n), where n is the number of employees. Storage Complexity: O(1).
Code
def average(salary: list[int]) -> float:
"""
Calculates the average salary of employees, excluding the minimum and maximum salaries.
Args:
salary (list[int]): A list of unique integers representing the salaries of employees.
Returns:
float: The average salary excluding the minimum and maximum salaries.
"""
min_salary = float('inf')
max_salary = float('-inf')
total_salary = 0
for s in salary:
min_salary = min(min_salary, s)
max_salary = max(max_salary, s)
total_salary += s
adjusted_salary_sum = total_salary - min_salary - max_salary
return adjusted_salary_sum / (len(salary) - 2)