Code giving the desired O/P but failing the test cases
Hey @Par1hsharma
We are given a circular array, print the next greater number for every element
you are doing wrong
try for this input :
4
8 2 3 6
correct output: -1 3 6 8
while(!stack.isEmpty() && arr[i%arr.length]>stack.peek())
WHY THIS LINE IS NOT HELPING IN THIS CODE
plz check
@Par1hsharma
We store the indices instead of the elements since there could be duplicates in the nums array.
correct code :
PLEASE EXPLAIN THESE LINES
if(ans[stack.peek()]==0) // ek hi baar update krna
ans[stack.pop()] = arr[i%n];
else
stack.pop();
}
@Par1hsharma
Actually we need to print next greater element.
Initially ans array each index will be occupied 0
if(ans[stack.peek()]==0) // first time encounter next greater element
ans[stack.pop()] = arr[i%n]; // update value
how is this c++ code implementing circular array so easily? I did the same thing in java but getting wrong output
#include
#include
using namespace std;
int main() {
int n;
cin>>n;
int a[10000];
for(int i=0;i<n;i++) cin>>a[i];
stack s;
s.push(a[0]);
for(int i=1;i<n;i++){
while(!s.empty()&&s.top()<a[i]){
cout<<a[i]<<" “;
s.pop();
}
s.push(a[i]);
}
while(!s.empty())
{
cout<<-1<<” ";
s.pop();
}
}
@Par1hsharma
these test cases are not available on backend
4
8 2 3 6
c ++ code will also fail
I have updated the test case.