Number of Employees Who Met the Target
Problem
There are n employees. Employee i worked hours[i] hours. The company requires every employee to work at least target hours. Return the number of employees who worked at least target hours, i.e. how many indices satisfy hours[i] >= target.
hours = [0,1,2,3,4], target = 23def numberOfEmployeesWhoMetTarget(hours, target):
count = 0 # employees who met the target
for h in hours: # scan every employee's hours
if h >= target: # worked at least target hours?
count += 1 # yes: include this employee
return count # total that met the target
function numberOfEmployeesWhoMetTarget(hours, target) {
let count = 0; // employees who met the target
for (const h of hours) { // scan every employee's hours
if (h >= target) { // worked at least target hours?
count++; // yes: include this employee
}
}
return count; // total that met the target
}
int numberOfEmployeesWhoMetTarget(int[] hours, int target) {
int count = 0; // employees who met the target
for (int h : hours) { // scan every employee's hours
if (h >= target) { // worked at least target hours?
count++; // yes: include this employee
}
}
return count; // total that met the target
}
int numberOfEmployeesWhoMetTarget(vector<int>& hours, int target) {
int count = 0; // employees who met the target
for (int h : hours) { // scan every employee's hours
if (h >= target) { // worked at least target hours?
count++; // yes: include this employee
}
}
return count; // total that met the target
}
Explanation
This is a single-pass counting problem. We never need to sort or store anything extra — we just look at each employee once and tally how many cleared the bar.
We keep one running variable count, starting at 0. As we walk the hours array from left to right, we test each value against target.
The condition is at least the target, so we use hours[i] >= target (greater-than-or-equal). An employee who worked exactly target hours does meet the requirement, which is why the boundary case is included.
Every time the test passes we increment count by one. After the loop finishes, count holds the number of employees who met the target, which we return.
Example: hours = [0,1,2,3,4], target = 2. The values 2, 3 and 4 pass the test while 0 and 1 fail, so the answer is 3.