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.
1# Take array2n = int(input("Enter array size: "))3arr = []4for i in range(n):5 arr.append(int(input(f"Element {i+1}: ")))67# Find second largest8if n < 2:9 print("Array too small")10else:11 # Find max12 max_val = max(arr)1314 # Find second max15 second_max = None16 for element in arr:17 if element != max_val:18 if second_max is None or element > second_max:19 second_max = element2021 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
Handle lists shorter than two.
- 2
Find the maximum and skip all equal entries.
- 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.
๐Related Content
- ๐
Phase 4 - Learn Concepts
Review Phase 4 concepts and explanations
- ๐
Phase 4 - Quiz
Test your Phase 4 understanding with quiz questions
- ๐ป
Phase 4 - All Practice Problems
Explore all practice problems for Phase 4
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum