I am solving this problem: Fraudulent Activity Notifications on HackerRank. I am done with my code and is working, but it is inefficient as well for very large inputs.
I don't know but after all my efforts, I am able to give out good solution to a problem of a MEDIUM LEVEL but this
timeout errorhappens every time for very large inputs. I have tried optimizing my code and still I get timeout errors. My agendas for this question and upcoming questions are:
- How to put efficiency for very large inputs. What kind of intellect it requires.
- How to reach to that level. What should I prepare for this.
- Code optimization
I am open to learning, and I am really desperate to learn how to write a more advanced and optimized code to make myself better. I am open to do hard work.
My Algorithm:
- For this problem we must go from
incrementing variable itilllen(givenArray)-d- Take a variable for the next variable to be compared, my case
iterateis the variable- Pass the values to the particular array to the method for counting
countFraud()- Add it to the count variable
- Increment iterate variable
Code:
# this is for counting the trailing array
def countFraud(arr, nextNum):
count = 0
median = 0.0
d = len(arr)
#for calculating the median correctly
arr.sort()
if d%2 != 0:
median = arr[int(d/2)]
else:
n = int(d/2)
median = (arr[n] + arr[n-1]) / 2
#now the opeartion for count from the array
if nextNum >= 2*median: count += 1
return count
# Complete the activityNotifications function below.
def activityNotifications(expenditure, d):
count = 0
iterate = d
# it will go upto the len of array - d, so that it will go upto the d length
# leaving the last element everytime for the comparision
for i in range(len(expenditure)-d):
count += countFraud(expenditure[i:iterate], expenditure[iterate])
iterate += 1
return count
Now previously I was doing two loops, adding the items to the new_array and passing it to the the countFraud(). But now I have optimized it and made it sort of O(N).
I don't know but this code is not getting submitted for all TCs due to Timeout Error. There is no problem in operation part. It is just with the efficiency of the code.
Timeout Error Input Example:
200000 10000
Link for input - Input Data
Expected Output:
633
I have read upon this article: HackerRank Environment to learn about the timing issue. For Python/Python 3 it is 10 seconds. My code is definitely taking more than that for values greater than 10^3 or 4.
My code has successfully passed 3 TCs though.