![]() |
VOOZH | about |
Given an array arr[] of size n, the task is to find all the Leaders in the array. An element is a Leader if it is greater than or equal to all the elements to its right side.
Note: The rightmost element is always a leader.
Examples:
Input: arr[] = [16, 17, 4, 3, 5, 2]
Output: [17 5 2]
Explanation: 17 is greater than all the elements to its right i.e., [4, 3, 5, 2], therefore 17 is a leader. 5 is greater than all the elements to its right i.e., [2], therefore 5 is a leader. 2 has no element to its right, therefore 2 is a leader.Input: arr[] = [1, 2, 3, 4, 5, 2]
Output: [5 2]
Explanation: 5 is greater than all the elements to its right i.e., [2], therefore 5 is a leader. 2 has no element to its right, therefore 2 is a leader.
Table of Content
Use two loops. The outer loop runs from 0 to size - 1 and one by one pick all elements from left to right. The inner loop compares the picked element to all the elements on its right side. If the picked element is greater than all the elements to its right side, then the picked element is the leader.
17 5 2
The idea is to scan all the elements from right to left in an array and keep track of the maximum till now. When the maximum changes its value, add it to the result. Finally reverse the result
17 5 2
Illustration:
arr[] = {16, 17, 4, 3, 5, 2}
Initially : maxRight = 2, res[] = { 2 }
- i = 4, maxRight = 5, res[] = { 2, 5 }
- i= 3, maxRight = 5, res[] = { 2, 5 }
- i = 2, maxRight = 5, res[] = { 2, 5 }
- i = 1, maxRight = 17, res[] = { 2, 5, 17 }
- i = 0, maxRight = 17, res[] = { 2, 5, 17 }
Reverse res[] = {17, 5, 2} and return