Find the largest and second largest value in a Linked List

• Last Updated : 18 Jun, 2021

Given a Linked List, the task is to find the largest and second largest value in a Linked List.
Example:

Input: LL = 10 -> 15 -> 5 -> 20 -> 7 -> 9
Output:
Largest = 20
Second Largest = 15
Input: LL = 0 -> 5 -> 52 -> 21
Output:
Largest = 52
Second Largest = 21

Approach:

1. Store the maximum of first two nodes in a variable max.
2. Store the minimum of first two nodes in a variable second_max.
3. Iterate over the remaining linked list. For each node:
• If current node value is greater than max, then set second_max as max and max as current node’s value.
• Else if current node value is greater than second_max, then set second_max as current node’s value.

Below is the implementation of the above approach:

Javascript


Output:
Largest = 20
Second Largest = 15

Performance Analysis

• Time Complexity: In the above approach, as we are iterating over the linked list only once, so the time complexity is O(N).
• Auxiliary Space Complexity: In the above approach, we are not using any extra space apart from a few constant size variables, so Auxiliary space complexity is O(1).

My Personal Notes arrow_drop_up