Skip to content

Commit eaca703

Browse files
author
Мето Трајковски
committed
Added a solution for finding the bussiest interval
1 parent 9c08a05 commit eaca703

1 file changed

Lines changed: 70 additions & 0 deletions

File tree

Lists/find_busiest_interval.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
'''
2+
Find the Busiest Interval
3+
4+
Given a list of arriving time and leaving time for each celebrity.
5+
Celebrity I, arrives at arriving[I] time and leaves at leaving[I] time.
6+
Output is the time interval that you want to go the party when the maximum number of celebrities are still there.
7+
8+
Input: arriving=[30, 0, 60], leaving=[75, 50, 150]
9+
Output: (30, 50) or (60, 75)
10+
11+
=========================================
12+
Just sort the lists, don't care about pairs ordering.
13+
And use a counter, when arriving counter++, when leaving counter--.
14+
Time Complexity: O(N LogN)
15+
Space Complexity: O(1)
16+
'''
17+
18+
19+
############
20+
# Solution #
21+
############
22+
23+
def bussiest_interval(arriving, leaving):
24+
# sort both arrays (don't care about pairs)
25+
arriving.sort()
26+
leaving.sort()
27+
28+
n = len(arriving)
29+
i, j = 0, 0
30+
start, end = 0, 0
31+
overlapping = 0
32+
max_overlapping = 0
33+
34+
# both arrays have same number of elements
35+
# but the biggest time is from the leaving array
36+
# becayse of that you're sure that 'i' will reach the end before 'j'
37+
while i < n:
38+
if arriving[i] <= leaving[j]:
39+
overlapping += 1
40+
if max_overlapping <= overlapping:
41+
max_overlapping = overlapping
42+
# save the start time if max_overlapping
43+
start = arriving[i]
44+
i += 1
45+
else:
46+
if max_overlapping == overlapping:
47+
# save the exit time if max_overlapping
48+
end = leaving[j]
49+
overlapping -= 1
50+
j += 1
51+
52+
# check again this to close the result interval because 'i' is completed and not 'j'
53+
if max_overlapping == overlapping:
54+
end = leaving[j]
55+
56+
# return start&end or max_overlapping
57+
return (start, end)
58+
59+
60+
###########
61+
# Testing #
62+
###########
63+
64+
# Test 1
65+
# Correct result => (30, 50) or (60, 75)
66+
print(bussiest_interval([30, 0, 60], [75, 50, 150]))
67+
68+
# Test 2
69+
# Correct result => (5, 5)
70+
print(bussiest_interval([1, 2, 10, 5, 5], [4, 5, 12, 9, 12]))

0 commit comments

Comments
 (0)