Second Largest Element

Arrays Fundamentals Easy
  • The underlying concept of finding the second largest number in an array is a crucial part of recommendation algorithms utilized in e-commerce platforms and streaming services
  • In these systems, it is often required not only to find the most relevant choice (the largest element), but also the next best alternatives (the second largest, third largest, etc
  • ) to provide users with a variety of options, hence improving user experience and engagement

Given an array of integers nums, return the second-largest element in the array. If the second-largest element does not exist, return -1.

Examples:

Input: nums = [8, 8, 7, 6, 5]

Output: 7

Explanation: The largest value in nums is 8, the second largest is 7

Input: nums = [10, 10, 10, 10, 10]

Output: -1

Explanation: The only value in nums is 10, so there is no second largest value, thus -1 is returned

Input: nums = [7, 7, 2, 2, 10, 10, 10]

Constraints

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104
  • nums may contain duplicate elements.

Hints

  • Use two variables to track the largest and second-largest elements as you iterate through the array. Update the second-largest only if you find an element smaller than the largest but larger than the current second-largest.
  • Avoid sorting, as a single traversal O(n) is sufficient to find the second-largest element.

Company Tags

Bloomberg Alibaba Epic Systems Seagate Technology HCL Technologies Lyft Unity Technologies Electronic Arts Visa Broadcom PwC JPMorgan Chase Databricks Ernst & Young Pinterest Red Hat Deloitte Reddit Stripe Intel HashiCorp Micron Technology Swiggy Texas Instruments Docker TCS Cognizant Accenture Infosys Capgemini Wipro