Given an integer array nums, return a list of all the leaders in the array.
A leader in an array is an element whose value is strictly greater than all elements to its right in the given array. The rightmost element is always a leader. The elements in the leader array must appear in the order they appear in the nums array.
Input: nums = [1, 2, 5, 3, 1, 2]
Output: [5, 3, 2]
Explanation: 2 is the rightmost element, 3 is the largest element in the index range [3, 5], 5 is the largest element in the index range [2, 5]
Input: nums = [-3, 4, 5, 1, -4, -5]
Output: [5, 1, -4, -5]
Explanation: -5 is the rightmost element, -4 is the largest element in the index range [4, 5], 1 is the largest element in the index range [3, 5] and 5 is the largest element in the range [2, 5]
Input: nums = [-3, 4, 5, 1, -30, -10]
The most naive thing that comes to mind is if at all any element on right is greater than the current element, then the current element can never be a leader.
leader
set at true initially which will tell if nums[i] is a leader or not.
leader
as false and break.
leader
equals true, if so add nums[i] to ans vector. Finally return the answer vector.#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
//Function to find leaders in an array.
vector<int> leaders(vector<int>& nums) {
vector<int> ans;
// Iterate through each element in nums
for (int i = 0; i < nums.size(); i++) {
bool leader = true;
/* Check whether nums[i] is greater
than all elements to its right*/
for (int j = i + 1; j < nums.size(); j++) {
if (nums[j] >= nums[i]) {
/* If any element to the right is greater
or equal, nums[i] is not a leader*/
leader = false;
break;
}
}
// If nums[i] is a leader, add it to the ans vector
if (leader) {
ans.push_back(nums[i]);
}
}
//Return the leaders
return ans;
}
};
int main() {
vector<int> nums = {1, 2, 5, 3, 1, 2};
// Create an instance of the Solution class
Solution finder;
// Get leaders using class method
vector<int> ans = finder.leaders(nums);
cout << "Leaders in the array are: ";
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
cout << endl;
return 0;
}
import java.util.*;
class Solution {
//Function to find leaders in an array.
public ArrayList<Integer> leaders(int[] nums) {
ArrayList<Integer> ans = new ArrayList<>();
// Iterate through each element in nums
for (int i = 0; i < nums.length; i++) {
boolean leader = true;
/* Check whether nums[i] is greater
than all elements to its right */
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] >= nums[i]) {
/* If any element to the right is greater
or equal, nums[i] is not a leader */
leader = false;
break;
}
}
// If nums[i] is a leader, add it to the ans list
if (leader) {
ans.add(nums[i]);
}
}
// Return the leaders
return ans;
}
}
class Main {
public static void main(String[] args) {
int[] nums = {1, 2, 5, 3, 1, 2};
// Create an instance of the Solution class
Solution finder = new Solution();
// Get leaders using class method
ArrayList<Integer> ans = finder.leaders(nums);
System.out.print("Leaders in the array are: ");
for (int leader : ans) {
System.out.print(leader + " ");
}
System.out.println();
}
}
class Solution:
# Function to find leaders in an array.
def leaders(self, nums):
ans = []
# Iterate through each element in nums
for i in range(len(nums)):
leader = True
'''Check whether nums[i] is greater
than all elements to its right'''
for j in range(i + 1, len(nums)):
if nums[j] >= nums[i]:
'''If any element to the right is greater
or equal, nums[i] is not a leader'''
leader = False
break
# If nums[i] is a leader, add it to the ans list
if leader:
ans.append(nums[i])
# Return the leaders
return ans
# Main method
nums = [1, 2, 5, 3, 1, 2]
# Create an instance of the Solution class
finder = Solution()
# Get leaders using class method
ans = finder.leaders(nums)
print("Leaders in the array are: ", end="")
for leader in ans:
print(leader, end=" ")
print()
class Solution {
// Function to find leaders in an array.
leaders(nums) {
let ans = [];
// Iterate through each element in nums
for (let i = 0; i < nums.length; i++) {
let leader = true;
/* Check whether nums[i] is greater
than all elements to its right */
for (let j = i + 1; j < nums.length; j++) {
if (nums[j] >= nums[i]) {
/* If any element to the right is greater
or equal, nums[i] is not a leader */
leader = false;
break;
}
}
// If nums[i] is a leader, add it to the ans array
if (leader) {
ans.push(nums[i]);
}
}
// Return the leaders
return ans;
}
}
// Main method
let nums = [1, 2, 5, 3, 1, 2];
// Create an instance of the Solution class
let finder = new Solution();
// Get leaders using class method
let ans = finder.leaders(nums);
console.log("Leaders in the array are: " + ans.join(" "));
Think of a parade where each person in a line holds a flag with a number on it, representing their importance. You start observing the parade from the last person, moving towards the front. Initially, the last person is the most important (since there's no one else behind them).
As you move forward, compare each person's flag number to the highest flag number seen so far. If someone's flag number is higher than the highest that is seen, they stand out as a leader because they have a higher number than anyone behind them.
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
//Function to find the leaders in an array.
vector<int> leaders(vector<int>& nums) {
vector<int> ans;
if(nums.empty()) {
return ans;
}
// Last element of the vector is always a leader
int max = nums[nums.size() - 1];
ans.push_back(nums[nums.size() - 1]);
// Check elements from right to left
for (int i = nums.size() - 2; i >= 0; i--) {
if (nums[i] > max) {
ans.push_back(nums[i]);
max = nums[i];
}
}
/* Reverse the vector to match
the required output order*/
reverse(ans.begin(), ans.end());
//Return the leaders
return ans;
}
};
int main() {
vector<int> nums = {10, 22, 12, 3, 0, 6};
// Create an instance of the Solution class
Solution finder;
// Get leaders using class method
vector<int> ans = finder.leaders(nums);
cout << "Leaders in the array are: ";
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
cout << endl;
return 0;
}
import java.util.*;
class Solution {
// Function to find the leaders in an array.
public ArrayList<Integer> leaders(int[] nums) {
ArrayList<Integer> ans = new ArrayList<>();
if (nums.length == 0) {
return ans;
}
// Last element of the array is always a leader
int max = nums[nums.length - 1];
ans.add(nums[nums.length - 1]);
// Check elements from right to left
for (int i = nums.length - 2; i >= 0; i--) {
if (nums[i] > max) {
ans.add(nums[i]);
max = nums[i];
}
}
/* Reverse the list to match
the required output order */
Collections.reverse(ans);
// Return the leaders
return ans;
}
}
class Main {
public static void main(String[] args) {
int[] nums = {10, 22, 12, 3, 0, 6};
// Create an instance of the Solution class
Solution finder = new Solution();
// Get leaders using class method
ArrayList<Integer> ans = finder.leaders(nums);
System.out.print("Leaders in the array are: ");
for (int leader : ans) {
System.out.print(leader + " ");
}
System.out.println();
}
}
class Solution:
# Function to find the leaders in an array.
def leaders(self, nums):
ans = []
if not nums:
return ans
# Last element of the list is always a leader
max_val = nums[-1]
ans.append(nums[-1])
# Check elements from right to left
for i in range(len(nums) - 2, -1, -1):
if nums[i] > max_val:
ans.append(nums[i])
max_val = nums[i]
'''Reverse the list to match
the required output order'''
ans.reverse()
# Return the leaders
return ans
# Main method
nums = [10, 22, 12, 3, 0, 6]
# Create an instance of the Solution class
finder = Solution()
# Get leaders using class method
ans = finder.leaders(nums)
print("Leaders in the array are: ", end="")
for leader in ans:
print(leader, end=" ")
print()
class Solution {
// Function to find the leaders in an array.
leaders(nums) {
let ans = [];
if (nums.length === 0) {
return ans;
}
// Last element of the array is always a leader
let max = nums[nums.length - 1];
ans.push(nums[nums.length - 1]);
// Check elements from right to left
for (let i = nums.length - 2; i >= 0; i--) {
if (nums[i] > max) {
ans.push(nums[i]);
max = nums[i];
}
}
/* Reverse the array to match
the required output order */
ans.reverse();
// Return the leaders
return ans;
}
}
// Main method
let nums = [10, 22, 12, 3, 0, 6];
// Create an instance of the Solution class
let finder = new Solution();
// Get leaders using class method
let ans = finder.leaders(nums);
console.log("Leaders in the array are: " + ans.join(" "));
Q: Why traverse the array from right to left?
A: Traversing from right to left ensures that the current maximum is always the leader for the elements processed so far. This avoids revisiting elements multiple times and allows a single-pass O(n) solution.
Q: How does the algorithm ensure the leaders appear in the correct order?
A: By adding leaders to a temporary list during right-to-left traversal and reversing the list at the end, the leaders are presented in the same order as they appear in the original array.
Q: How would you handle an unsorted list with duplicate elements?
A: The presence of duplicate elements does not change the logic. The algorithm still traverses from right to left and checks if the current element is greater than the maximum seen so far. Only elements that strictly satisfy this condition are added to the leader list.
Q: What if the array is circular?
A: For a circular array, you would need to iterate over the array twice (once normally and once wrapping around). Adjust the comparison logic to handle the circular property, ensuring no duplicates are considered as leaders.