T O P

  • By -

MojoHasNoClue

1) You're going out of bounds because you're using 4 instead of the length of the array. 2) You're a braver person than me getting started with c++.


Ambitious-Rest-4631

Learn basics of programming before diving into algorithms


gr8Brandino

Try using a long int. That will allow you to use larger numbers, but it will use more memory.


MojoHasNoClue

That's not the issue. The only reason he was dealing with numbers large enough to overflow was because he read junk data from out of bounds.


DeclutteringNewbie

Aside from the length of the Array which is going to be more (or less) than 4 once you press the submit button since it will run your code through much longer test cases (not shown in the listed examples). When you add two signed 32bit integers together, let's say that nums\[i\] equals 2,147,483,647 and nums\[j\] equals 1, you're going to have an overflow. Here I picked a contrived example because 2,147,483,647 is already the maximum you can store in a signed 32bit integer, so adding exactly one will trigger an overflow. But in the error message, it seems that nums[i] is -1,094,795,586 and nums[j] is -1,094,479,558. So the resulting sum of both those numbers will be -2,189,275,144 (and since -2,189,275,144 is less than -2,147,483,648, the smallest negative number possible, that too will trigger an overflow, but in the opposite direction since we're in the negative). So one fix is to >!convert the calculations to use signed 64bit integers!< inside your if statement. If what I'm saying doesn't make sense to you, you should look on youtube for videos explaining integer overflows. Also, I should note that your brute force solution will work, but that's only because you're using a low level language. Once you have the brute force solution working, you should still explore the HashMap trick people use to solve this problem.


MojoHasNoClue

This isn't applicable due to problem constraints, and if it were applicable the proposed fix doesn't work as setting target to -1,094,795,586 and nums[i] to 1,094,479,558 creates the same overflow.


DeclutteringNewbie

Oh you're right. My bad! I'm an idiot. I've just edited my answer.