![]() |
VOOZH | about |
Given a linked list of integers, the task is to find a peak element in the given linked list. An element is a peak, if it is greater than or equals to its neighbors. For boundary elements, consider only one neighbor.
Examples:
Input : List = {1 -> 6 -> 8 -> 4 -> 12}
Output : 8
Explanation: In this list, 8 is greater than both its neighbors (6 and 4), making it a peak element. Other elements do not satisfy the peak condition.Input : List = {1->2->3->4}
Output : 4
Explanation: The list is strictly increasing. In such cases, the last element (4) is always a peak, as it is greater than its only neighbor (3).
Approach:
To find a peak element in a linked list, we need to identify a node that is greater than or equal to its neighbors. Start from the beginning of the list and compare each node with the next one. If we find a node that is greater than or equal to the next node, it’s a peak, return it.
Notice, we only check the current node with next node, why not with previous node? Because, in the previouse iteration we have already checked the same and if prev was not peak it means it must be smaller than current element).
If we reach the end of the list without finding such a node, check if the last node is greater than or equal to the previous node; if so, it’s a peak.
Below is the implementation of the above approach:
4
Time Complexity: O(N) where N is the number of elements in the linked list.
Auxiliary Space: O(1)