Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1873. Calculate Special Bonus - Leetcode Solution

Problem Description

The "Calculate Special Bonus" problem requires you to process a list of employees, each with a unique employee_id and a name. For each employee, you need to compute a bonus value based on the following rules:

  • If the employee_id is an odd number and the name does not start with the character 'M', then the bonus is equal to the salary of that employee.
  • Otherwise, the bonus is 0.

The output should return a list of employees with their employee_id and corresponding bonus, sorted by employee_id in ascending order.

Key constraints:

  • Each employee_id is unique.
  • Do not reuse or modify input data outside the specified rules.

Thought Process

When approaching this problem, the first step is to clarify the filtering rules: we need to check two conditions for each employee — whether their employee_id is odd and whether their name does not start with 'M'. If both are true, we assign their salary as their bonus; otherwise, the bonus is zero.

The naive approach would be to iterate through each employee, check the conditions, and assign the bonus accordingly. Since there are no complex dependencies or relationships between employees, we don't need to worry about advanced data structures or algorithms.

The main optimization is simply to process each record in a single pass, applying the rules directly. This is efficient and straightforward.

Solution Approach

Let's break down the solution step by step:

  1. Iterate through the employee list: For each employee, retrieve their employee_id, name, and salary.
  2. Check conditions:
    • Is employee_id odd? (You can check this by employee_id % 2 == 1)
    • Does name NOT start with 'M'? (You can check this by name[0] != 'M' or using string methods)
  3. Assign bonus:
    • If both conditions are met, set bonus = salary.
    • Otherwise, set bonus = 0.
  4. Store the result: For each employee, create a record with their employee_id and computed bonus.
  5. Sort the output: After processing all employees, sort the results by employee_id in ascending order.

This approach is efficient because it only requires a single pass through the data and uses simple operations for filtering and assignment. No extra data structures are needed beyond a list to store the output.

Example Walkthrough

Let's consider the following sample input:

  • { "employee_id": 2, "name": "Alice", "salary": 100 }
  • { "employee_id": 3, "name": "Bob", "salary": 200 }
  • { "employee_id": 7, "name": "Mary", "salary": 300 }
  • { "employee_id": 5, "name": "Tom", "salary": 400 }

Now, let's process each employee:

  1. Alice: employee_id is 2 (even), so bonus = 0.
  2. Bob: employee_id is 3 (odd), name does not start with 'M', so bonus = 200.
  3. Mary: employee_id is 7 (odd), name starts with 'M', so bonus = 0.
  4. Tom: employee_id is 5 (odd), name does not start with 'M', so bonus = 400.

The output, sorted by employee_id:

  • { "employee_id": 2, "bonus": 0 }
  • { "employee_id": 3, "bonus": 200 }
  • { "employee_id": 5, "bonus": 400 }
  • { "employee_id": 7, "bonus": 0 }

Time and Space Complexity

Brute-force approach:

  • Time complexity: O(n), where n is the number of employees, since we check each employee once.
  • Space complexity: O(n) for storing the output list.
Optimized approach:
  • Time complexity: O(n), as above, since every employee is processed in a single pass.
  • Space complexity: O(n), also as above.

There is no meaningful difference between brute-force and optimized approaches in this problem, as the most direct solution is already optimal.

Summary

The key to solving the "Calculate Special Bonus" problem is to apply the filtering rules directly and efficiently as you process each employee. By checking the employee_id and name conditions, you can assign the correct bonus in a single pass. The solution is straightforward, efficient, and easy to implement, making it a good example of how clear problem requirements can lead to an elegant and simple algorithm.

Code Implementation

def calculate_special_bonus(employees):
    # employees: List[dict] with keys 'employee_id', 'name', 'salary'
    result = []
    for emp in employees:
        eid = emp['employee_id']
        name = emp['name']
        salary = emp['salary']
        if eid % 2 == 1 and not name.startswith('M'):
            bonus = salary
        else:
            bonus = 0
        result.append({'employee_id': eid, 'bonus': bonus})
    # Sort by employee_id
    result.sort(key=lambda x: x['employee_id'])
    return result
      
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

struct Employee {
    int employee_id;
    string name;
    int salary;
};

struct Result {
    int employee_id;
    int bonus;
};

vector<Result> calculateSpecialBonus(vector<Employee>& employees) {
    vector<Result> result;
    for (const auto& emp : employees) {
        int bonus = 0;
        if (emp.employee_id % 2 == 1 && (emp.name.empty() || emp.name[0] != 'M')) {
            bonus = emp.salary;
        }
        result.push_back({emp.employee_id, bonus});
    }
    sort(result.begin(), result.end(), [](const Result& a, const Result& b) {
        return a.employee_id < b.employee_id;
    });
    return result;
}
      
import java.util.*;

class Employee {
    int employee_id;
    String name;
    int salary;
    Employee(int id, String n, int s) {
        employee_id = id;
        name = n;
        salary = s;
    }
}

class Result {
    int employee_id;
    int bonus;
    Result(int id, int b) {
        employee_id = id;
        bonus = b;
    }
}

public class Solution {
    public List<Result> calculateSpecialBonus(List<Employee> employees) {
        List<Result> result = new ArrayList<>();
        for (Employee emp : employees) {
            int bonus = 0;
            if (emp.employee_id % 2 == 1 && !emp.name.startsWith("M")) {
                bonus = emp.salary;
            }
            result.add(new Result(emp.employee_id, bonus));
        }
        result.sort(Comparator.comparingInt(a -> a.employee_id));
        return result;
    }
}
      
function calculateSpecialBonus(employees) {
    // employees: Array of objects {employee_id, name, salary}
    let result = [];
    for (let emp of employees) {
        let bonus = 0;
        if (emp.employee_id % 2 === 1 && !emp.name.startsWith('M')) {
            bonus = emp.salary;
        }
        result.push({employee_id: emp.employee_id, bonus: bonus});
    }
    result.sort((a, b) => a.employee_id - b.employee_id);
    return result;
}