Skip to content

Commit 307bd4a

Browse files
committed
Leaders in an array
1 parent 2df51be commit 307bd4a

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
"""
2+
Problem Link: https://www.interviewbit.com/problems/leaders-in-an-array/
3+
4+
Problem Description
5+
Given an integer array A containing N distinct integers, you have to find all the leaders in the
6+
array A.
7+
An element is leader if it is strictly greater than all the elements to its right side.
8+
NOTE:The rightmost element is always a leader.
9+
10+
Problem Constraints
11+
1 <= N <= 105
12+
1 <= A[i] <= 108
13+
14+
Input Format
15+
First and only argument is an integer array A.
16+
17+
Output Format
18+
Return an integer array denoting all the leader elements of the array.
19+
NOTE: Ordering in the output doesn't matter.
20+
21+
Example Input
22+
Input 1:
23+
A = [16, 17, 4, 3, 5, 2]
24+
25+
Input 2:
26+
A = [1, 2]
27+
28+
Example Output
29+
Output 1:
30+
[17, 2, 5]
31+
32+
Output 2:
33+
[2]
34+
35+
Example Explanation
36+
Explanation 1:
37+
Element 17 is strictly greater than all the elements on the right side to it.
38+
Element 2 is strictly greater than all the elements on the right side to it.
39+
Element 5 is strictly greater than all the elements on the right side to it.
40+
So we will return this three elements i.e [17, 2, 5], we can also return [2, 5, 17]
41+
or [5, 2, 17] or any other ordering.
42+
43+
Explanation 2:
44+
Only 2 the rightmost element is the leader in the array.
45+
"""
46+
class Solution:
47+
# @param A : list of integers
48+
# @return a list of integers
49+
def solve(self, A):
50+
res = []
51+
max_num = float('-inf')
52+
for i in range(len(A)-1, -1, -1):
53+
if A[i] > max_num:
54+
res.append(A[i])
55+
max_num = A[i]
56+
return res

0 commit comments

Comments
 (0)