
Suppose given ‘WARRIOR_ARR’ is [ 4, 5, 3, 7, 4 ]
So we return [ -1, 0, -1, 2, 2 ] as ‘ANSWER’.
For the first warrior (index 0), there is no warrior with a smaller responding time on his left. So, 'ANSWER[0]' = -1.
For the second warrior (index 1), the warrior with a smaller responding time (4) and at the nearest position on the left side is at index ‘0’. So, 'ANSWER[1]' = 0.
For the third warrior (index 2), there is no warrior with a smaller responding time on his left. So, 'ANSWER[2]' = -1.
For the fourth warrior (index 3), the warrior with a smaller responding time (3) and at the nearest position on the left side is at index '2'. So, 'ANSWER[3]' is 2.
For the fifth warrior (index 4), the warrior with a smaller responding time (3) and at the nearest position on the left side is at index '2'. So, 'ANSWER[4]' is 2.
The first line of input contains a ‘T’ number of test cases.
The first line of each test case contains an integer ‘N’ i.e size of the array/list ‘WARRIOR_ARR’.
The second line of each test case contains an array ‘WARRIOR_ARR’, where ‘WARRIOR_ARR[i]’ denotes the responding time of ‘i-th’ warrior.
For each test case, return the ‘ANSWER’ array/list.
You are not required to print anything explicitly. It has already been taken care of. Just implement the function.
1 <= ‘T’ <= 100
1 <= ‘N’ <= 10 ^ 3
1 <= ‘WARRIOR_ARR[i]’ <= 10 ^ 6
Time Limit: 1 second
The idea here is to use the brute force approach.
For each index, we traverse in the left side of the ‘WARRIOR_ARR’ starting from that index, and if we find a smaller element, we store its index in ‘ANSWER’. Else we store ‘-1’ for that element.
The idea here is to use the stack because as we know all push, pop operations take O(1) time. If the element in the stack is greater than the current element we pop the element from the stack, and if we found a smaller element we push it into the stack and also stored that index.