Given 3 integers A, B and C, return the smallest number.
You are not allowed to use built-in functions such as min
Example 1:
Input: A = 7, B = 4, C = 9 Output: 4
Example 2:
Input: A = 3, B = 8, C = 3 Output: 3
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 minimum value?
A is the minimum value if A <= B and A <= C. We can write an if statement checking these conditions and if they hold, return A:
if A <= B and A <= C:
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 minimum value if B <= A and B <= C. We can write an if statement checking these conditions and if they hold, return B:
if A <= B and A <= C:
return A
if B <= A and B <= C:
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:
if A <= B and A <= C:
return A
if B <= A and B <= C:
return B
return C
While the solution above is very good, we propose another one which is more scalable (i.e. works better for a larger number of values). It involves going throught the numbers and using a variable
minVal to store the minimum one found so far:
minVal = A
if B < minVal:
minVal = B
if C < minVal:
minVal = C
return minVal
Please watch the video solution for a better understanding of this solution.
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