Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Find Second Largest

Find the second distinct largest value in a list. Students skip every maximum, track a nullable candidate, and distinguish distinct rank from sorted position.

AdvancedPhase 4 - Level 5: Logical & AppliedExample 3 of 14
find-second-largest.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Find second largest
8if n < 2:
9 print("Array too small")
10else:
11 # Find max
12 max_val = max(arr)
13
14 # Find second max
15 second_max = None
16 for element in arr:
17 if element != max_val:
18 if second_max is None or element > second_max:
19 second_max = element
20
21 if second_max is None:
22 print("All elements are same")
23 else:
24 print(f"Second largest: {second_max}")

Output

Enter array size: 5
Element 1: 10
Element 2: 5
Element 3: 20
Element 4: 15
Element 5: 20
Second largest: 15

In this one

  • Rank distinct values
  • Use None for no candidate
  • Handle all-equal input

How it works

  1. 1

    Handle lists shorter than two.

  2. 2

    Find the maximum and skip all equal entries.

  3. 3

    Keep the largest remaining value or report no second value.

Edge cases

What does [9, 9, 7] return?

What does [9, 9, 7] return?

Seven, the next distinct value.

What if all entries are equal?

What if all entries are equal?

The program prints All elements are same.

What's going on

The code first finds max_val. It then ignores values equal to that maximum while searching for the largest remaining value.

second_max begins as None so all-negative input works without a false numeric sentinel. Arrays shorter than two get one message; arrays with only one distinct value get another. Repeated maxima do not occupy the second distinct rank.

What does [9, 9, 7] return? Seven, the next distinct value.

What if all entries are equal? The program prints All elements are same.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why begin second_max as None?

Pick an answer to check it.

Question 2

What does [9, 9, 7] return?

Pick an answer to check it.

Questions people ask

What does [9, 9, 7] return?

Seven, the next distinct value.

What if all entries are equal?

The program prints All elements are same.

Why begin second_max as None?

No candidate has been found yet.