Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Number of Programmer Worked on given Time in Python
Suppose we have a list of intervals and another input time. In each interval, the structure is [start, end], representing the times when a programmer worked. We have to find the number of programmers that were working at a given time.
So, if the input is like intervals = [[2, 6], [4, 10], [5, 9], [11, 14]], time = 5, then the output will be 3 as at time 5, there are three programmers working: [2, 6], [4, 10], [5, 9].
Algorithm
To solve this, we will follow these steps −
- Initialize count := 0
- For each interval in intervals, do
- If start of interval <= time and end of interval >= time, then
- count := count + 1
- If start of interval <= time and end of interval >= time, then
- Return count
Implementation
Let us see the following implementation to get better understanding ?
class Solution:
def solve(self, intervals, time):
count = 0
for interval in intervals:
if interval[0] <= time and interval[1] >= time:
count += 1
return count
# Create instance and test
ob = Solution()
intervals = [[2, 6], [4, 10], [5, 9], [11, 14]]
time = 5
result = ob.solve(intervals, time)
print(f"Number of programmers working at time {time}: {result}")
The output of the above code is ?
Number of programmers working at time 5: 3
Alternative Approach
We can also solve this using a simple function without a class ?
def count_programmers_at_time(intervals, time):
"""Count how many programmers are working at given time"""
count = 0
for start, end in intervals:
if start <= time <= end:
count += 1
return count
# Test with the same example
intervals = [[2, 6], [4, 10], [5, 9], [11, 14]]
time = 5
result = count_programmers_at_time(intervals, time)
print(f"Programmers working at time {time}: {result}")
# Test with different time
time = 12
result = count_programmers_at_time(intervals, time)
print(f"Programmers working at time {time}: {result}")
Programmers working at time 5: 3 Programmers working at time 12: 1
How It Works
The algorithm checks each interval to see if the given time falls within the range [start, end]. For each interval where start <= time <= end, we increment the counter. This gives us the total number of overlapping intervals at the specified time.
Time Complexity
The time complexity is O(n) where n is the number of intervals, as we need to check each interval once. The space complexity is O(1) as we only use a constant amount of extra space.
Conclusion
This problem is solved by iterating through all intervals and counting how many contain the given time point. The solution is straightforward with linear time complexity and can be implemented either as a class method or a simple function.
