I tried solving a problem on HackerRank, called 'Apple and orange', here's the code:
def countApplesAndOranges(s, t, a, b, apples, oranges):
count_apples = 0
count_oranges = 0
x = [x for x in range(s, t+1)]
pos_apple = [apple + a for apple in apples]
pos_orange = [orange + b for orange in oranges]
for i in x:
for j in pos_apple:
if j == i:
count_apples +=1
for l in pos_orange:
if l == i:
count_oranges += 1
print(count_apples)
print(count_oranges)
The code works. However, when I try submitting it, it passes the first 3 tests and fails the rest with the exception 'Terminated due to timeout'. I checked out the input from one of the tests and it's a huge amount of data to process, you can take a look at the data here: https://hr-testcases-us-east-1.s3.amazonaws.com/25220/input03.txt?AWSAccessKeyId=AKIAR6O7GJNX5DNFO3PV&Expires=1642016820&Signature=J4ypdP0YzRxcOWp%2By5XaD5ITeMw%3D&response-content-type=text%2Fplain
It fails cause it takes like 2 minutes to process the code with the same input via my IDE, but the HackerRank tests are limited to 10 seconds.
I need your help to optimize the code and get it to run faster.
Nested loops seem to be the biggest problem here, but I have no idea what should I replace the with.