Number of Employees Who Met the Target (LeetCode 2798): Solution and Explanation
Each employee has a number of hours worked. Count how many of them worked at least target hours.
Intuition
Picture the hours as bars and draw a horizontal line at height target. The answer is the number of bars that touch or cross that line.
Each bar is judged on its own, so a single comparison per employee is all the work there is.
The test is "at least", so a bar that ends exactly on the line counts.
Approach: Single pass with a counter
- Set
count = 0. - For each value
hinhours, ifh >= target, add 1 tocount. - Return
count.
Step-by-step example
hours = [0,1,2,3,4], target = 2
- 0 and 1 are below 2, so count stays 0.
- 2 equals the target, so count becomes 1.
- 3 is above 2, so count becomes 2.
- 4 is above 2, so count becomes 3.
- Return 3.
Code: Python, Java, C++
1class Solution:
2 def numberOfEmployeesWhoMetTarget(self, hours: List[int], target: int) -> int:
3 count = 0
4 for h in hours:
5 if h >= target:
6 count += 1
7 return count1class Solution {
2 public int numberOfEmployeesWhoMetTarget(int[] hours, int target) {
3 int count = 0;
4 for (int h : hours) {
5 if (h >= target) {
6 count++;
7 }
8 }
9 return count;
10 }
11}1class Solution {
2public:
3 int numberOfEmployeesWhoMetTarget(vector<int>& hours, int target) {
4 int count = 0;
5 for (int h : hours) {
6 if (h >= target) {
7 count++;
8 }
9 }
10 return count;
11 }
12};Time and space complexity
O(n)
Every employee is compared with the target exactly once.
O(1)
Only the counter is stored.
Other approaches
Built-in counting (time O(n), space O(1))
Write the same pass as one expression, for example sum(h >= target for h in hours) or a stream filter and count.
Sort and binary search (time O(n log n), space O(1) to O(n))
Sort the hours and find the first index with a value of at least target. It answers many different targets quickly, but for a single target it is slower than one pass.
Common mistakes
- Using
>instead of>=. An employee with exactly target hours met the target. - Forgetting that target can be 0, in which case every employee counts.
- Summing the hours instead of counting the employees.
Frequently asked questions
Does an employee with exactly target hours count?
Yes. The requirement is at least target hours, so equality passes.
Is there a faster approach than O(n)?
No. Every value has to be looked at once, because any unread employee could change the count.
What if target is 0?
Hours are never negative, so every employee meets a target of 0 and the answer is n.