Social feed~12 min2s · 256 MBtarget O(n) time, O(1) spacetraversal
A social app ends each day with a "most liked" board. Every post has a like count, and the board shows the post in first place and the post in second place.
Two posts can have the same count. They then take places one and two together, so the runner-up has the same count as the winner. You are asked for the like count in second place.
Write second_largest(likes).
likes[i] is the number of likes of post i. There are at least two posts.Input: likes = [40, 90, 90, 15, 70]
Output: 90The table shows the two highest counts after each post.
| Post | Likes | Best | Second |
|---|---|---|---|
| 0 | 40 | 40 | -1 |
| 1 | 90 | 90 | 40 |
| 2 | 90 | 90 | 90 |
| 3 | 15 | 90 | 90 |
| 4 | 70 | 90 | 90 |
Posts 1 and 2 both have 90 likes. They take first and second place together, so the output is 90. The value -1 means that no count has been seen yet.
Input: likes = [5, 8]
Output: 5With two posts, the smaller count is in second place: 5.
Input: likes = [3, 3, 3]
Output: 3Three posts with the same count fill places one, two and three. The runner-up count is 3.
2 ≤ likes.length ≤ 100,000 (posts in a day)0 ≤ likes[i] ≤ 1,000,000,000Sorting the whole list costs about n × log n steps, roughly 1.7 × 10^6 at n = 100,000. That is fast enough, but only two numbers matter. One pass that keeps the two best counts needs n steps and two variables.