What is wrong with this approach..2 tc are failed?
hi anshul,
Your logic and code is absolutely correct for the single direction array, but this question is for circular array.
4
4 1 2 3
In this test case answer will be
-1 3 4 1
Please let me know if you have any other doubt.
So what must be the correction for circular array plz tell
hey anshul,
For circular array you can just copy the array as it is to make it 2*n,e.g.
4 1 2 3 is the array, make it 4 1 2 3 4 1 2 3.
But I just found the main mistake for which your code is not working,
Try this test case in your code
6
1 2 3 1 2 4
Your code is giving this output:-
2 3 2 4 4 -1
Correct output should be
2 3 4 2 4 -1
what should be the correction?
please answer to this one
hey anshul,
Sorry for the late reply.
You have to do this question by storing pair of int,value for each element.
At last you will have to print answer of every index.
plz provide the code…i dont know how to make the circular array
Hi anshul,
Here is the tutorial with the code and in this i have explained in comments also.
vector nextGreaterElements(vector &nums)
{
int n = nums.size();
vector<int> res(n);
stack<int> s;
// 2*n loop because we will have to go to start again from the end
// as it is a cirular array.
for (int i = 2 * n - 1; i >= 0; i--)
{
while (!s.empty() && nums[s.top()] <= nums[i % n])
{
s.pop();
}
res[i % n] = (s.empty() ? -1 : nums[s.top()]);
//Here we are storing the value of array if stack is not empty
// and if it is empty then -1.
s.push(i % n);
//In this we are pushing the index by doing mod with n because:-
// lets say our array size is 5 and we have reached at 6th index that means
// we have to go to index 1 of our array
// Hence 6%5 is 1
}
return res;