2798. Number of Employees Who Met the Target
Problem Description
You are given a company with n
employees, numbered from 0
to n - 1
. Each employee has worked a certain number of hours, represented in an array called hours
. The value hours[i]
tells you how many hours employee i
has worked.
The company has a policy that requires every employee to work at least target
hours. Your task is to count how many employees have met or exceeded this requirement.
You need to:
- Take an array
hours
containing non-negative integers representing each employee's working hours - Take a non-negative integer
target
representing the minimum required hours - Return the count of employees who have worked
target
hours or more
For example, if hours = [5, 1, 4, 2, 3]
and target = 3
, you would check each employee:
- Employee 0: worked 5 hours (≥ 3) ✓
- Employee 1: worked 1 hour (< 3) ✗
- Employee 2: worked 4 hours (≥ 3) ✓
- Employee 3: worked 2 hours (< 3) ✗
- Employee 4: worked 3 hours (≥ 3) ✓
So the answer would be 3 employees.
The solution uses a simple counting approach - iterate through each element in the hours
array and count how many values are greater than or equal to target
. The expression sum(x >= target for x in hours)
creates a generator that produces True
(counted as 1) for each employee meeting the target and False
(counted as 0) otherwise, then sums them up to get the total count.
Intuition
The problem asks us to count employees who meet a certain condition - working at least target
hours. This is a classic counting problem where we need to check each element against a criteria.
When we need to count how many elements in an array satisfy a condition, the most straightforward approach is to:
- Look at each element one by one
- Check if it meets our condition
- Keep a running count of those that do
Since we need to examine every employee to determine if they've met the target, we can't avoid looking at each element at least once. This means our best possible time complexity is O(n)
.
The key insight is that this is a simple filtering and counting operation. For each employee's hours x
, we only care about one thing: is x >= target
? This is a boolean check that evaluates to either True
or False
.
In Python, we can leverage the fact that True
equals 1
and False
equals 0
when used in arithmetic operations. So instead of writing a loop with an explicit counter:
count = 0 for x in hours: if x >= target: count += 1
We can use a more concise approach with sum()
and a generator expression: sum(x >= target for x in hours)
. This generates a sequence of boolean values (one for each employee), and sum()
treats them as 1s and 0s, effectively counting the True
values.
This solution is optimal because:
- We must check every employee (can't do better than
O(n)
time) - We only need constant extra space (just the counter)
- The logic is simple and direct - no need for sorting, complex data structures, or multiple passes through the data
Solution Approach
The solution uses an iteration and counting pattern to solve this problem. Let's walk through the implementation step by step:
Algorithm:
- Iterate through each element in the
hours
array - For each element
x
, check ifx >= target
- Count the number of elements that satisfy this condition
- Return the final count
Implementation Details:
The solution leverages Python's built-in sum()
function combined with a generator expression to create a concise one-liner:
return sum(x >= target for x in hours)
Here's how this works:
for x in hours
- This iterates through each element in the hours arrayx >= target
- For each element, this comparison returns a boolean value:True
if the employee worked at leasttarget
hoursFalse
otherwise
- The generator expression
(x >= target for x in hours)
produces a sequence of boolean values sum()
adds up these boolean values, where:True
is treated as1
False
is treated as0
- The result is the total count of employees who met the target
Example Walkthrough:
If hours = [5, 1, 4, 2, 3]
and target = 3
:
- The generator produces:
[True, False, True, False, True]
- Which corresponds to:
[1, 0, 1, 0, 1]
when summed sum()
returns:1 + 0 + 1 + 0 + 1 = 3
Time and Space Complexity:
- Time Complexity:
O(n)
wheren
is the length of the hours array, as we need to check each employee exactly once - Space Complexity:
O(1)
as we only use a constant amount of extra space for the counter (the generator doesn't create a full list in memory)
This approach is optimal because we must examine every employee to determine the count, making O(n)
the best possible time complexity for this problem.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through a small example to illustrate the solution approach.
Given: hours = [2, 5, 1, 4]
and target = 3
Step 1: We'll iterate through each employee's hours and check if they meet the target.
Step 2: Process each element:
-
Employee 0:
hours[0] = 2
- Check:
2 >= 3
? →False
- This evaluates to
0
when counted
- Check:
-
Employee 1:
hours[1] = 5
- Check:
5 >= 3
? →True
- This evaluates to
1
when counted
- Check:
-
Employee 2:
hours[2] = 1
- Check:
1 >= 3
? →False
- This evaluates to
0
when counted
- Check:
-
Employee 3:
hours[3] = 4
- Check:
4 >= 3
? →True
- This evaluates to
1
when counted
- Check:
Step 3: Sum up the results:
- The generator expression
(x >= target for x in hours)
produces:False, True, False, True
- When passed to
sum()
, these boolean values become:0 + 1 + 0 + 1 = 2
Result: 2 employees have worked at least 3 hours.
The beauty of this approach is its simplicity - we're essentially creating a series of yes/no answers (1s and 0s) for each employee and adding them up to get our final count. No explicit counter variable or if-statements needed!
Solution Implementation
1class Solution:
2 def numberOfEmployeesWhoMetTarget(self, hours: List[int], target: int) -> int:
3 """
4 Count the number of employees who worked at least the target number of hours.
5
6 Args:
7 hours: List of integers representing hours worked by each employee
8 target: Integer representing the minimum hours threshold
9
10 Returns:
11 Integer count of employees who met or exceeded the target hours
12 """
13 # Use generator expression with sum to count employees meeting the target
14 # For each hour value, check if it meets or exceeds the target
15 # True evaluates to 1 and False to 0 when summed
16 return sum(hour_value >= target for hour_value in hours)
17
1class Solution {
2 /**
3 * Counts the number of employees who met or exceeded the target hours.
4 *
5 * @param hours An array containing the number of hours worked by each employee
6 * @param target The minimum number of hours required to meet the target
7 * @return The count of employees who worked at least the target number of hours
8 */
9 public int numberOfEmployeesWhoMetTarget(int[] hours, int target) {
10 // Initialize counter for employees who met the target
11 int count = 0;
12
13 // Iterate through each employee's hours
14 for (int employeeHours : hours) {
15 // Check if current employee met or exceeded the target
16 if (employeeHours >= target) {
17 count++;
18 }
19 }
20
21 // Return the total count of employees who met the target
22 return count;
23 }
24}
25
1class Solution {
2public:
3 /**
4 * Counts the number of employees who worked at least the target number of hours.
5 *
6 * @param hours - Vector containing the number of hours worked by each employee
7 * @param target - Minimum number of hours required to meet the target
8 * @return The count of employees who worked hours greater than or equal to the target
9 */
10 int numberOfEmployeesWhoMetTarget(vector<int>& hours, int target) {
11 // Use count_if algorithm to count elements that satisfy the condition
12 // Lambda function checks if each hour value meets or exceeds the target
13 return count_if(hours.begin(), hours.end(),
14 [target](int hour_value) {
15 return hour_value >= target;
16 });
17 }
18};
19
1/**
2 * Counts the number of employees who met or exceeded the target hours
3 * @param hours - Array of hours worked by each employee
4 * @param target - Minimum number of hours required to meet the target
5 * @returns The count of employees who worked at least the target hours
6 */
7function numberOfEmployeesWhoMetTarget(hours: number[], target: number): number {
8 // Filter employees whose hours are greater than or equal to target
9 // and return the count
10 return hours.filter((hoursWorked: number) => hoursWorked >= target).length;
11}
12
Time and Space Complexity
The time complexity is O(n)
, where n
is the length of the array hours
. This is because the solution iterates through each element in the hours
array exactly once to check if it meets or exceeds the target
value. The generator expression (x >= target for x in hours)
creates a single pass through the array, and the sum()
function consumes this generator, performing a constant-time comparison operation for each element.
The space complexity is O(1)
. The generator expression doesn't create an intermediate list or array; instead, it yields values one at a time as sum()
consumes them. The only additional space used is for the counter variable maintained by sum()
and the temporary variable for iteration, both of which require constant space regardless of the input size.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Type Confusion with Boolean Values
A common mistake is attempting to explicitly convert the boolean result to an integer or misunderstanding how Python handles boolean values in arithmetic operations.
Incorrect approach:
# Overly verbose and unnecessary
return sum(1 if x >= target else 0 for x in hours)
# Or trying to cast explicitly
return sum(int(x >= target) for x in hours)
Why it's a pitfall: While these work, they add unnecessary complexity. Python automatically treats True
as 1
and False
as 0
in numeric contexts.
Solution: Trust Python's boolean-to-integer conversion:
return sum(x >= target for x in hours)
2. Using Filter with Len Instead of Sum
Some developers might use filter()
and len()
to solve this problem:
Incorrect approach:
return len(list(filter(lambda x: x >= target, hours)))
Why it's a pitfall: This creates an intermediate list in memory, which is inefficient for large datasets. It has O(n)
space complexity instead of O(1)
.
Solution: Use the generator expression with sum()
to maintain constant space complexity.
3. Manual Loop with Counter Variable
Beginners often write verbose solutions with explicit counters:
Overly complex approach:
count = 0 for hour in hours: if hour >= target: count += 1 return count
Why it's a pitfall: While correct, this is unnecessarily verbose for such a simple operation. It's harder to read and maintain.
Solution: Use Python's functional programming features for cleaner, more readable code.
4. Forgetting Edge Cases
Not handling edge cases properly:
Potential issues:
- Empty
hours
array target = 0
(all employees meet the requirement)- All employees have 0 hours with
target > 0
Solution: The generator expression naturally handles these cases:
- Empty array returns
0
target = 0
correctly counts all employees- No special handling needed for zero hours
The beauty of sum(x >= target for x in hours)
is that it elegantly handles all these edge cases without additional code.
Which of the tree traversal order can be used to obtain elements in a binary search tree in sorted order?
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!