Tutorialspoint
Problem
Solution
Submissions

Find the Second Largest Number in a List

Certification: Basic Level Accuracy: 45.12% Submissions: 82 Points: 10

Write a Python program that finds the second largest number in a given list of integers. If all elements are equal or there are fewer than 2 elements, return -1.

Example 1
  • Input: nums = [10, 5, 7, 15, 20]
  • Output: 15
  • Explanation:
    • Step 1: Find the largest number in the list: 20.
    • Step 2: Find the largest number that is not equal to the largest: 15.
    • Step 3: Return 15 as the second largest number.
Example 2
  • Input: nums = [3, 3, 3, 3]
  • Output: -1
  • Explanation:
    • Step 1: Find the largest number in the list: 3.
    • Step 2: Try to find a number less than 3, but all elements are equal.
    • Step 3: Since all elements are equal, return -1.
Constraints
  • 0 ≤ len(list) ≤ 10^6
  • List elements are integers
  • Time Complexity: O(n)
  • Space Complexity: O(1)
NumberListTech MahindraSnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Sort the list and return the second last element if there are at least two unique numbers
  • Track both maximum and second maximum while iterating through the list
  • Handle edge cases like empty lists, lists with one element, or lists with all identical elements

Steps to solve by this approach:

 Step 1: Check if the list has at least 2 elements, return -1 if not.

 Step 2: Initialize two variables to track the largest and second largest values.
 Step 3: Iterate through each number in the input list.
 Step 4: If current number is larger than the largest, update both largest and second largest.
 Step 5: If current number is between largest and second largest, update only second largest.
 Step 6: Check if a valid second largest was found (not still the initial value).
 Step 7: Return the second largest number or -1 if all elements are equal.

Submitted Code :