Why did i get TLE for my solution for BINADD?

https://www.codechef.com/viewsolution/28366024

i dont understand why i got a TLE for the above solution!Someone please explain.

@kaiyu Defect is here:
unsigned int diff = a.length() - b.length();
When b.length() is greater than a.length() then it’s trying to assign negative value into a unsigned variable BUT it’s impossible, that’s why the variable diff holds a large garbage value something like this: 12
Therefor a large loop and TLE

...
else if(b.length()>a.length()) {
  for (int i = 0; i < diff; ++i) { // large loop - hence TLE
    a='0'+a;
  }
}

Enjoy coding :heart_eyes:

2 Likes

ohhh!

Thank youu for your help.

@kaiyu It’s my pleasure :slightly_smiling_face:

@kaiyu , One more defect,

in the case when b.length() < a.length(),
you are adding 0’s in b using this method

for (int i = 0; i < diff; ++i) {
    b = '0' + b;
}

Time complexity of b = '0' + b; itself is linear in size of string. (link)
So, complexity for whole for loop become O(n^2). That’s is pretty slow.

USE THIS
b.insert(b.begin(), diff, '0');
It’s complexity is linear in size of new string.

Checkout difference here.

Always be careful with string operations. :smile:

4 Likes

@deep529 Welcome to CC Discuss :heart_eyes: and Congratulations for the 4 stars :+1:

2 Likes

Thank you @smile_forever for a warm welcome!:blush:

2 Likes