I am solving a problem which states the following: There is a row of buckets numbered from 1 to n. A gardener fills this buckets in a particular fashion. He fills the buckets between two ends l and r including l and r with 1<=l<=r<=n. He does this for k times. We need to find the bucket which is having water equal to the median of volumes in the buckets. I am using a program of time complexity knlgn to solve this. The input is like this: the first line contain n and k seperated by spaces and the next k lines contain pairs l and r for each watering process. I am using an algorithm of nklgn to solve this as follows:
while True:
nk = input().split(' ')
n = int(nk[0])
k = int(nk[1])
a = input().split(' ')
for z in range(len(a)):
a[z] = int(a[z])
if n==0 and k==0: break
for mn in range(k):
(x, y) = input().split(' ')
x = int(x)-1
y = int(y)-1
for z in range(x, y+1):
a[z] += 1
print(sorted(a)[int(len(a)/2)])
Please help me solve this using a better algorithm and I have encountered a very similar problem at least 3 to 4 times. You may give me some hint in the answer if not entire code.