New update is available. Click here to update.

Last Updated: 10 Nov, 2020

Easy

```
1. Rightmost element is always a leader.
2. The order of elements in the return sequence must be the same as the given sequence
```

```
The given sequence is 13, 14, 3, 8, 2 .
13 Not a leader because on the right side 14 is greater than 13.
14 lt is a leader because no one greater element in the right side.
3 Not a leader because on the right side 8 are greater than 3.
8 It is a leader because no one greater element on the right side.
2 It is a leader because it is the rightmost element in a sequence.
Hence there are 3 leaders in the above sequence which are 14, 8, 2.
```

```
The first line of input contains an integer βTβ denoting the number of test cases.
The first line of each test case contains an integer βNβ denoting the number of elements in the given sequence.
The second line of each test case contains βNβ space-separated integers denoting the elements in the sequence.
```

```
For each test case, print a sequence of all leaders separated by space on a separate line.
```

```
You don't need to print anything, it has been already taken care of. Just implement the given function.
```

```
1 <= T <= 50
1 <= N <= 10^4
-10^9 <= ELEMENTS[i] <= 10^9
Where βELEMENTS[i]β denotes an element at position βiβ in the sequence.
Time limit: 1 sec
```

Approaches

The steps are as follows:

- We use two loops.
- The outer loop runs from left to right of the sequence using a variable INDEXβ, and in a single instance of the iteration βINDEXβ will represent the index of each element of the sequence.
- The inner loop runs from βINDEX + 1β to the end of the sequence using a variable βrightIndexβ, in which βrightIndexβ will point to the element that is on the right side of the element and will be picked by the outer loop.
- If element picked by the outer loop is greater than all the elements of picked by inner loop then element picked by the outer loop is the leader.
- Finally, return the answer sequence.

- Start iterating from right to left in the sequence.
- Keep the highest element in a variable βMAXIMUMβ.
- If we find any element greater than the variable βMAXIMUMβ then update the βMAXIMUMβ variable to the current element and add the current element in the βANSWERβ sequence.
- Finally, return the βANSWERβ sequence.

Similar problems