+ 7
[Solved] Why does the following code lead to Timeout?
I came across this issue in a HackerRank Problem Problem link:https://www.hackerrank.com/contests/acm-vit-cpp/challenges/a-new-operation My solution was to return xor of the numbers.. Solution: https://code.sololearn.com/WqG2hIQfp60P The solution worked for Test case-01 for the remaining test cases the output was runtime error(Terminated due to timeout) So what exactly is the issue in my code and how do i optimize my code for the same??
3 odpowiedzi
+ 3
replace while(count!=num.length) with while(count<num.length),
because while(count!=num.length) only becomes true when count is exactly num.length, but if (num.length % 2!=0) then its never going to be true. e.g
count = 0
num.length=5
while(count!=num.length) {
count+=2
console.log(count)
}
Output:
2
4
6
8
10
...
You are cought in the while loop and never are able to exit it. Thats why its terminates due to timeout.
The fix as mentioned above while(count<num.length) checks if count is smaller e.g
count=0
num.length=7
while(count<num.length){
count+=2
console.log(count)
}
Output:
2
4
6
it stops at 6 because 6+2=8 and 8 ist not < num.length
Correct me if this is not the answer you were looking for, in case I didn't get the issue
0
Well I'll surely try this answer Jakob Meier thanks for your efforts... Will respond if it works or not.. 👍 :)
0
Thank you Jakob Meier well it works ..It also proves i need improvement with algorithms..🙁