Find The Second Largest Item - Heap & Tracking Approach (Beginner Big N Interview Question) @BackToBackSWE
Find The Second Largest Item - Heap & Tracking Approach (Beginner Big N Interview Question)  @BackToBackSWE
Uploaded January 2019 | Updated November 2026, 2 days ago
Free 5-Day Mini-Course: backtobackswe.com
Try Our Full Platform: backtobackswe.com/pricing
πŸ“Ή Intuitive Video Explanations
πŸƒ Run Code As You Learn
πŸ’Ύ Save Progress
❓New Unseen Questions
πŸ”Ž Get All Solutions

Question: Given an array that may or may not be sorted, find the second largest item.

Approach 1 (Single Pass)

We keep track of a variable for the maximum number and keep track of a variable for the minimum number.

We do a linear traversal.

We keep track of a firstMax and a secondMax.

If the element is greater than firstMax:
firstMax becomes secondMax.
the element becomes firstMax.

Otherwise, if the first element is larger than secondMax and it is not the firstMax:
the element becomes secondMax.


The key thing here is to realize the case where the element might not dominate firstMax but it might still dominate the secondMax but it cannot dominate the secondMax if it is firstMax or else we will lose our actual secondMax.

At the end if secondMax is still not defined then we do not have an answer, otherwise, secondMax is our answer.


Complexities

Time: O( n )
n is the length of the array

Space: O( 1 )
we do not create anything past local variables that are primitives


Approach 2 (Min Heap)

We can use a min heap to hold at maximum 2 items. A min-heap will always have the smallest item available to us so we can get rid of it to only keep the k largest items.

it is almost like we need to think in opposites:
to extract the k max elements we use a min heap.
to extract the k min elements we use a max heap.

This is because the heap type desired corresponds to the item that we care the least about. To find maxes we don't care about mins. To find mins we don't care about maxes.

Every time we add a 3rd item we eject the smallest item from the min heap.

By the end of the traversal, we can just eject what our min heap held and that will be the 2nd largest item in the array.

Complexities

Time: O( n * log(2) ) = O( n )

insertion and removal from the heap will always take log(2) which is O( 1 ) time ("constant") assuming that it is a balanced binary heap.

We traverse an array of length n.

Space: O( 2 ) = O ( 1 )

The space used for the min heap will always be constant.


Critical that you keep in mind:
empty cases [ ]
cases where there is only 1 item [ 2 ]
cases where there are repeated items [ 3, 3, 3, 3, 3, 3 ], etc.

++++++++++++++++++++++++++++++++++++++++++++++++++

HackerRank: youtube.com/channel/UCOf7UPMHBjAavgD0Qw5q5ww

Tuschar Roy: youtube.com/user/tusharroy2525

GeeksForGeeks: youtube.com/channel/UC0RhatS1pyxInC00YKjjBqQ

Jarvis Johnson: youtube.com/user/VSympathyV

Success In Tech: youtube.com/channel/UC-vYrOAmtrx9sBzJAf3x_xw
Find The Second Largest Item - Heap & Tracking Approach (Beginner Big N Interview Question)How To Reverse A Singly Linked List | The Ultimate Explanation (Iteratively & Recursively)Clone A Linked List (With Random Pointers) - Linear Space Solution & Tricky Constant Space SolutionTotal Occurrences Of K In A Sorted Array (Facebook Software Engineering Interview Question)Implement An LRU Cache - The LRU Cache Eviction Policy (LRU Cache on LeetCode)Depth First & Breadth First Graph Search - DFS & BFS Graph Searching AlgorithmsSearch A Maze For Any Path - Depth First Search Fundamentals (Similar To The Maze on Leetcode)Why Comparison Based Sorting Algorithms Are Ξ©(n*lg(n))Implement A Queue Using Stacks - The Queue ADT (Implement Queue Using Stacks on LeetCode)Test If A Binary Tree Is Symmetric (Symmetric Tree on Leetcode)3 Mistakes Beginners Make When First Learning Java and Android DevelopmentTotal Ways To Decode A String - Recursive Dynamic Programming Approach (Decode Ways on LeetCode)
Back To Back SWE |

Find The Second Largest Item - Heap & Tracking Approach (Beginner Big N Interview Question)

SHARE TO X SHARE TO REDDIT SHARE TO FACEBOOK WALLPAPER