Middle of three numbers using minimum comparisons in PythonIn many Competitive exams, we encounter problems in finding the middle number. It is also important to consider the constraints given in the problem, like minimum comparisons. Let's see different solutions to the problem. 1. Traditional ApproachIn the traditional approach, using mathematical calculation, the middle element will be found. In the first step, the total of three numbers is calculated, and then the maximum and minimum values from the list are retrieved using the max and min functions. Now, the middle element is calculated by subtracting min and max from the total. The approach is efficient in terms of the readability of the code and the complexity of computation. Code Output: Approach 5 Output: 5 3 7 Time Complexity : O(1) Space Complexity: O(1) 2. Conditional StatementsIf else statements are used in this approach to compare the numbers and then find the middle element. This approach is less efficient. Code Output: Approach 5 Output: 5 3 7 Time Complexity : O(1) Space Complexity: O(1) 3. SortingIn this approach, all the elements are sorted according to ascending order, and then the middle element is found. With the goal of finding the middle value, this is not efficient as the computation complexity is very low for this approach. Code Output: Approach 5 Output: 5 3 7 Time Complexity : O(1) Space Complexity: O(1) 4. Bitwise OperatorsBitwise operators are used for the comparison, and then the middle element is found. These operators are not commonly used for these tasks, but for minimum comparisons, bitwise operators are a better choice. This approach is efficient but not readable. Code Output: Approach 5 Output: 5 3 7 Time Complexity : O(1) Space Complexity: O(1) 5. Ternary OperatorTernary operator 'x if condition else y' is used to find the middle element. This is used for a better readable and compact solution. The approach is efficient in terms of the readability of the code and the complexity of computation. Code Output: Approach 5 Output: 5 3 7 Time Complexity : O(1) Space Complexity: O(1) |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India