Runtime error in practice problem ANUUND(ups and downs) of may cook off

I am getting runtime error in following problem
ups and down

my code is giving right answer for the given test cases but i am getting
SIGABRT
please help

this is my code

Okay, Your whole code is fine except the for loop :

for(i=0;i<n&&k<n;i++)
{
      arr2[k++] = arr[i];
      arr2[k++] = arr[n-i-1];
}

Now suppose n = 3 and sorted arr={1,2,3}

for i=0…

in arr2 you place 2 element 1 and then 3. till here i=0 , k= 2. Loop continue again , as k<3 (which is your n)

for i=1 …

in arr2 you AGAIN PLACE 2 ELEMNETS … What are those 2 elements ?

            arr2[2]=arr[1] 
            arr2[3]= arr[1] 

But size of arr2 was 3 i.e. from 0 to 2 only … Strange if you run this program output it shows till n i.e. 3 places only but in reality you crossed limit of array and corrupted the memory.Such case will arise only when n is odd . So , here’s a corrected form of for loop you can use :

for(i=0;i<n/2;i++) // i< n/2 , not i<n 
{
    arr2[k++] = arr[i];
    arr2[k++] = arr[n-i-1];
}

if(n%2==1) 
   arr2[k++]=arr[i];

i<n/2 as for each i you place 2 elements in array, so by the time you reach n/2 , you would have placed 2*(n/2) = n elements in arr2 , except when n is odd , as n/2 is not an integer. Hence for that one element we again have “if(n%2==1)” condition outside the loop.

what about “k<n” condition ? That is not at all required !! .
Here’s the link to corrected solution.

1 Like

please ask questions in the editorial page of the problem itself, it would have better chances of getting replies.

thanks alot for your guidance
now i got it
thanks…:slight_smile:

//