Middle Of Three

Easy
0/40
Average time to solve is 15m
profile
Contributed by
60 upvotes
Asked in company
MAQ Software

Problem statement

You have been given three distinct integers ‘X’, ‘Y’ and ‘Z’. You need to find the number with a value in the middle.

For example :

X = 4, Y = 6, Z = 2
Here the element with value in the middle is 4, because 2 < 4 < 6.

Note :

You need to try doing it using minimum comparisons.
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line contains a single integer ‘T’ representing the number of test cases. 

The first line of each test case will contain three space-separated distinct integers ‘X’, ‘Y’, and ‘Z’.
Output Format :
For each test case, print the number with a value in the middle.

Output for every test case will be printed in a separate line.
Note :
You don’t need to print anything, It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 50
1 <= X, Y, Z <= 10^9

Where ‘T’ is the number of test cases.
Where ‘X’, ‘Y’, and ‘Z’ denote the distinct numbers.

Time limit: 1 sec
Sample Input 1 :
2
2 3 1
6 8 9   
Sample Output 1 :
2 
8
Explanation of sample input 1 :
In the first test case, the three numbers are 2, 3 and 1. The middle element is 2, as 1 < 2 < 3

In the second test case, the three numbers are 6, 8 and 9. The middle element is 8, as 6 < 8 < 9
Sample Input 2 :
2
15 2 3
2 3 4
Sample Output 2 :
3
3
Explanation for sample input 2 :
In the first test case, the three numbers are 15, 2 and 3. The middle element is 3, as 2 < 3 < 15

In the second test case, the three numbers are 2, 3 and 4. The middle element is 3, as 2 < 3 < 4
Hint

Can you think of checking each element?

Approaches (3)
Naive

The basic idea is to check for each element to be the middle element. Steps are as follows:

  1. Check for X
    • If Y is less than X AND simultaneously X is less than Z, OR, if Z is less than X AND simultaneously X is less than Y, then X is the middle element, hence return X.
  2. If the above conditions are not true, then check for Y
    • If X is less than Y AND simultaneously Y is less than Z, OR, if Z is less than Y AND simultaneously Y is less than X, then Y is the middle element, hence return Y.
  3. If these conditions are also not true, then neither X nor Y is the middle elements, which implies that Z is the middle element, hence return Z.

The number of comparisons: 8, in the worst case.

Time Complexity

O(1)

 

Since we are always doing linear comparisons irrespective of input, the time complexity will be O(1).

Space Complexity

O(1)

 

Since we are not using any extra space, the overall space complexity will be O(1).

Code Solution
(100% EXP penalty)
Middle Of Three
Full screen
Console