Problem Link - Second Largest Practice Problem in 500 to 1000 difficulty problems
Problem Statement:
Three numbers A, B and C are the inputs. Write a program to find second largest among them.
Approach:
Approach 1:
This approach directly compares the three integers using conditional statements to find the second largest number.
Steps:
- Compare A,B, and C using conditional checks:
- If A is greater than B and less than C, or A is greater than C and less than B, A is the second largest.
- Similarly, check B and C with the same logic.
- Print the number that satisfies the condition for each test case.
Approach 2:
This approach involves storing the numbers in an array and using the sort
function to find the second largest.
Steps:
- Store the integers A,B,C in an array.
- Sort the array in ascending order.
- Print the second element in the sorted array, which will be the second largest.
Complexity:
- Time Complexity: For both the approaches we have time complexity of
O(1)
. Using simple if-else and sorting three integers requiresO(1)
. - Space Complexity:
O(1)
No extra space used.