[Solved] Why does the following code lead to Timeout? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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??

3rd May 2020, 8:34 AM
$hardul B
$hardul B - avatar
3 Answers
+ 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
4th May 2020, 5:20 AM
Jakob Meier
Jakob Meier - avatar
0
Well I'll surely try this answer Jakob Meier thanks for your efforts... Will respond if it works or not.. 👍 :)
4th May 2020, 8:54 AM
$hardul B
$hardul B - avatar
0
Thank you Jakob Meier well it works ..It also proves i need improvement with algorithms..🙁
4th May 2020, 9:49 AM
$hardul B
$hardul B - avatar