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
The problem requires us to find the smallest of three given integers A, B, and C without using built-in functions like min
. The input consists of three integers, and the output should be the smallest of these integers.
Input: A = 7, B = 4, C = 9 Output: 4
The core challenge is to determine the smallest of three numbers without using built-in functions. This problem is fundamental in understanding basic conditional statements and comparisons. It has applications in various fields such as sorting algorithms, decision-making processes, and more.
To solve this problem, we can use conditional statements to compare the three numbers. We will start by comparing A with B and C, then B with A and C, and finally, if neither A nor B is the smallest, C will be the smallest by default.
The naive solution involves directly comparing the numbers using if-else statements. This approach is straightforward but not scalable for a larger number of values.
An optimized approach involves using a variable to keep track of the minimum value found so far. This method is more scalable and can be easily extended to more than three numbers.
minVal
with the value of A.minVal
. If B is smaller, update minVal
to B.minVal
. If C is smaller, update minVal
to C.minVal
as the smallest number.def find_minimum(A, B, C):
# Initialize minVal with A
minVal = A
# Compare B with minVal
if B < minVal:
minVal = B
# Compare C with minVal
if C < minVal:
minVal = C
# Return the smallest value
return minVal
# Test cases
print(find_minimum(7, 4, 9)) # Output: 4
print(find_minimum(3, 8, 3)) # Output: 3
The time complexity of this approach is O(1) because we are performing a constant number of comparisons regardless of the input size. The space complexity is also O(1) as we are using a fixed amount of extra space.
Consider the following edge cases:
To test the solution comprehensively, consider a variety of test cases:
When approaching such problems, consider the following tips:
In this blog post, we discussed how to find the minimum of three numbers without using built-in functions. We explored a naive solution and an optimized approach, provided a detailed algorithm, and analyzed the complexity. Understanding such fundamental problems is crucial for developing problem-solving skills and preparing for more complex challenges.
For further reading and practice, consider the following resources: