Problem Breakdown
The objective is to simulate an SQL query in Python. We need to process a list of employee records where each record contains employee_id, name, and salary. The logic requires filtering employees whose names begin with the character ‘A’ (case-insensitive) and increasing their salary by 10%. The output must be a new collection containing only these modified records.
Intuition
The problem maps directly to an SQL SELECT statement with a WHERE clause (name LIKE 'A%'). In Python, we replicate this using iteration or filtering. Since the dataset size is typically manageable in interview contexts (), a single pass solution is optimal. We must be careful not to use floating-point arithmetic that introduces precision errors (e.g., salary * 1.1 might yield 279.999999). Using Python’s built-in round() function handles standard rounding requirements effectively, approximating SQL behavior for integer salaries.
Approach
- Initialize Result: Create an empty list to store the updated employee records.
- Iterate and Filter: Loop through each dictionary in the input list. Check if the name is non-empty and starts with ‘A’ (case-insensitive).
- Calculate Adjustment: For matching employees, compute
new_salary = round(salary * 1.1). This ensures standard rounding behavior rather than truncation or incorrect boolean arithmetic tricks found in flawed drafts. - Store Result: Append a dictionary containing the original ID and new salary to the result list.
- Return Output: Return the populated list of dictionaries.
Complexity Analysis
- Time Complexity: where is the number of employees in the input list. We traverse the list exactly once, performing constant-time string checks and arithmetic operations for each element.
- Space Complexity: where is the number of qualifying employees (those starting with ‘A’). This space is required to store the output result set. Auxiliary space excluding the output is .
Solution
def calculate_salaries(employees):
"""
Calculates 10% salary increase for employees whose name starts with 'A'.
Args:
employees (List[Dict]): List of dicts with keys 'employee_id', 'name', 'salary'
Returns:
List[Dict]: List containing employee_id and new_salary for qualifying employees.
"""
target_prefix = "A" # Matches the standard LC problem condition
result = []
for emp in employees:
name = emp.get("name", "")
salary = emp["salary"]
if len(name) > 0 and name[0].upper() == target_prefix.upper():
new_salary = int(round(salary * 1.1)) # Standard rounding to nearest integer
result.append({
"employee_id": emp["employee_id"],
"new_salary": new_salary
})
return result
# Example usage:
if __name__ == "__main__":
data = [
{"employee_id": 1, "name": "Alice", "salary": 200},
{"employee_id": 2, "name": "Bob", "salary": 300}
]
print(calculate_salaries(data))
Edge Cases Handled
- Empty Name: The check
len(name) > 0prevents index errors if a name is empty or null. - Case Sensitivity: Using
.upper()ensures ‘alice’ matches the target prefix ‘A’, handling case-insensitive requirements common in real-world data unless strict SQL collation rules apply (which usually default to case-insensitivity for names). - No Matches: If no employees start with the prefix, an empty list is returned naturally by Python’s logic flow without crashing.
- Rounding Precision: Using
round()handles floating point arithmetic correctly compared to truncating or using boolean flags (True/False) which can lead to incorrect integer values for salaries ending in .5 (e.g., 279.5).