⬅ Previous Topic
Next Permutation of ArrayNext Topic ⮕
Longest Consecutive Sequence in Array⬅ Previous Topic
Next Permutation of ArrayNext Topic ⮕
Longest Consecutive Sequence in ArrayTopic Contents
Given an array of integers, your task is to find all the leader elements in the array.
You need to return a list of all such leaders in left-to-right order as they appear in the array.
arr
.leaders
to store leader elements.max_from_right = arr[n-1]
.max_from_right
to the leaders
list.max_from_right
, update max_from_right
and add it to leaders
.leaders
list to maintain left-to-right order.def find_leaders(arr):
n = len(arr)
leaders = []
max_from_right = arr[-1]
leaders.append(max_from_right)
for i in range(n - 2, -1, -1):
if arr[i] > max_from_right:
max_from_right = arr[i]
leaders.append(max_from_right)
leaders.reverse()
return leaders
# Sample Input
arr = [16, 17, 4, 3, 5, 2]
print("Leaders:", find_leaders(arr))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | The array is scanned from right to left once, and each element is checked only once, making the operation linear. |
Average Case | O(n) | Regardless of input distribution, the array is always scanned once from end to start to compare with the running maximum. |
Average Case | O(n) | In the worst case (e.g., strictly decreasing array), every element becomes a leader, but the time taken remains linear as there is still only one pass. |
O(n)
Explanation: The worst-case space is O(n) if all elements are leaders and stored in the list. Additional space is used only for the leaders list and a few variables.
⬅ Previous Topic
Next Permutation of ArrayNext Topic ⮕
Longest Consecutive Sequence in ArrayYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.