For problem: D1. Dances (Easy version)
My approach: I sorted both arrays in increasing order. Then, using two pointers i
and j
for arrays b
and a
respectively, initially pointing to the last element. I move both pointers to the left in the case where a[j] < b[i]
. Otherwise, I use a while loop to find the first element to the left of pointer j
that is less than b[i]
, adding the count of the number of elements of a
I skipped.
Initially, I forgot to put a check on the value of j
in case it becomes less than 0
, which could result in a runtime error as I will try to access an element out of the bound. Surprisingly, it got accepted when calling the function by passing copy of the vector, and the same code resulted in a runtime error when called by passing the vector as a reference.
Here are my submissions:
Submission 1 passing vector as reference without check on j
. Runtime error because j
can become < 0
and I will try to access an undefined address.
Submission 2 passing copy of vector without check on j
. Accepted. Why it's not giving runtime error similar to Submission 1.
Submission 3 passing vector as reference with check on j
. Accepted.
Can you help me understand why Submission 2 got accepted even though it should give runtime error similar to Submission 1.
Thank you.
Sometimes you are so unlucky that memory corruption is not detected ;)