Find the greater element segmentation fault

code link : https://pastebin.com/SH7pAyAJ
My code get’s abnormally terminated please look into it, highlight the cause and correct it.

Hey @Divya_321 in this while loop of stack !s.empty() would come before the s.top() < p[i] So, instead of while(s.top()<p[i] && !s.empty()), this would come while( !s.empty() && s.top()<p[i]) . We have to do this because in the earlier case even if s was empty your code would try to compare s.top() with p[i] but since s is empty it would throw an error but in the later case if s would have been empty the first condition of and would become false and it wouldn’t check the second conditions which means no errors.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

hey @keshavgupta0103 this is my code link : https://pastebin.com/KTJj13Kk
first of all thank you for my clearing my concept and correcting and pointing my bugs but than also I am getting tle is there any to optimize the my code

Hey @Divya_321 you are trying to iterate the array circularly and that is causing problems i would suggest you to make an array of 2n elements so if the original array was 1 2 3 make an array 1 2 3 1 2 3 and then iterate it linearly to solve the problem.
Please refer this code for the same:

I am unable to understand your approach may you explain it a bit specially “cin >> a[i], a[i + n] = a[i];” can we write it like this

this part : -
for(int i = 0; i < n; i++)
cin >> a[i], a[i + n] = a[i];
int res[2n];
memset(res, -1, sizeof(res));
stack st;
for(int i = 0; i < 2
n; i++){
while(!st.empty() && a[st.top()] < a[i]){
res[st.top()] = i%n + 1;
st.pop();
}
st.push(i);
}

@keshavgupta0103 please explain your code and give some comments

The logic behind inserting the 2n elements instead of n is that in this way we can get the elements that were behind the current element in the front as well for example if the original array was 4 1 2 3 the 2n array would be 4 1 2 3 4 1 2 3, we can see that in the initial array for 4 we would have to rotate but in the new array we dont need to do that, in this case the solution for the first n elements would be correct.