


Your task is to return an array of integers answer,
where ans[i] = next_larger(node_{i+1}).
Input: 2 - >1 -> 5
Output: ans = [5,5,0]
Here for the first node village, the village with a stronger ninja is present with a strength of 5, therefore ans[0] = 5.
Similarly ans[1] = 5 and since there are no villages after node 3 with stronger ninjas, therefore, ans[2] = 0
The first line of input contains a single integer ‘T’ denoting the number of test cases.
The second line contains single space-separated integers, denoting the elements of the linked list with -1 being the last element denoting the end of the list (or null element).
Return an array of integers answer, where ans[i] = next_larger(node_{i+1}).
Print the output of each test case in a separate line.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 100
1 <= N <= 5000
1 <= node.val <=10^9
where 'N' is the size of the linked list and 'node.value' is the value of a node.
Time Limit : 1 sec
We will iterate through the given linked list of elements (nodes) with the help of two nested loops. Where we will check for every node whether there exists a next node with a value bigger than the value of current node and subsequently build the ‘ans’ list (array) and return it.
The algorithm will be-
The main observation here is that the above naive approach can be optimized by maintaining a monotonically decreasing stack of elements traversed. If a greater element is found, then append it to the resultant linked list ‘L’ else append 0.
The algorithm will be -