Difficulty: Easy | Acceptance: 87.80% | Paid: No Topics: Array
There are n employees in a company, numbered from 0 to n - 1. Each employee i has worked for hours[i] hours in the company.
The company requires each employee to work for at least target hours.
You are given a 0-indexed integer array hours of length n and an integer target.
Return the number of employees who worked at least target hours.
Table of Contents
- Examples
- Constraints
- Linear Iteration
- Functional Approach
Examples
Input: hours = [0,1,2,3,4], target = 2
Output: 3
Explanation: The company requires employees to work at least 2 hours.
- Employee 0 worked 0 hours and did not meet the target.
- Employee 1 worked 1 hour and did not meet the target.
- Employee 2 worked 2 hours and met the target.
- Employee 3 worked 3 hours and met the target.
- Employee 4 worked 4 hours and met the target.
There are 3 employees who met the target.
Input: hours = [5,1,4,2,2], target = 6
Output: 0
Explanation: The company requires employees to work at least 6 hours.
There are 0 employees who met the target.
Constraints
n == hours.length
1 <= n <= 50
0 <= hours[i], target <= 10⁵
Linear Iteration
Intuition We iterate through the array once, checking each employee’s hours against the target. If the hours are greater than or equal to the target, we increment our counter.
Steps
- Initialize a counter variable to 0.
- Loop through each element in the hours array.
- For each element, check if it is greater than or equal to the target.
- If the condition is true, increment the counter.
- Return the counter after the loop finishes.
class Solution:
def numberOfEmployeesWhoMetTarget(self, hours: List[int], target: int) -> int:
count = 0
for h in hours:
if h >= target:
count += 1
return countComplexity
- Time: O(n)
- Space: O(1)
- Notes: This is the most efficient approach with minimal space usage.
Functional Approach
Intuition We utilize built-in array methods to filter the list for employees meeting the target and then count the resulting elements. This abstracts the loop logic.
Steps
- Use the language’s filter or stream mechanism to select elements >= target.
- Return the count or length of the filtered collection.
class Solution:
def numberOfEmployeesWhoMetTarget(self, hours: List[int], target: int) -> int:
return sum(1 for h in hours if h >= target)Complexity
- Time: O(n)
- Space: O(n) or O(1) depending on implementation (filter creates new array, count_if is O(1) extra)
- Notes: More concise but may have slightly higher constant factors or memory overhead depending on the language implementation.