Given 3 integers (the parameters A, B and C; Rust and Go name them in lowercase), return the second largest number.
Example 1:
Input: A = 7, B = 3, C = 9 Output: 7
Example 2:
Input: A = 12, B = 8, C = 3 Output: 8
Note:
Your algorithm should run in O(1) time and use O(1) extra space.
Hints:
There are three candidates to the solution:
A, B and C. We should try out each of them until we find the correct one.
How can we check if A is the solution? What should happen for A to be the second largest value?
A is the second largest value if the smaller of B and C is less than or equal to A, and A is less than or equal to the larger of B and C. We can write an if statement checking these two conditions and, if they hold, return A.
What if the conditions don't hold and A is not the solution? What should we do next?
We should test
B. Similarly, B is the second largest value if the smaller of A and C is less than or equal to B, and B is less than or equal to the larger of A and C. We can write a second if statement checking these conditions and, if they hold, return B.
What if not even B is the solution?
Then, it's clear that
C is the solution, so we should return C. We don't even need to check the conditions anymore.
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
