TCS Digital Capability Assessment - Ques 2 - 20th march 2021
Write a program to find the Nth largest element from an array of numbers.
Instructions:
- The system does not allow any kind of hard coded input value/values.
- The written program code by the candidate will be verified against the inputs that are supplied from the system.
- or more clarification, please read the following points carefully till the end.
Input Format:
The first input contains integer value X, used for defining the size of array.
The second input contains X unsorted distinct integer numbers separated by new line, i.e. A[i].
The third input contains the value of N, to find the Nth largest element from the array.
Output Format:
The output should be an integer value, the Nth largest element in the array.
Additional message in the output will result in the failure of test cases.
There must be an error message as "INVALID INPUT" if the same integer is input more than once.
Constraints:
1 <= X <= 10
1 <= A[i] <= 1000
1 <= N <= X
Example 1:
Input:
5
10
20
40
30
60
Output:
30
Explanation:
In the Given input,
5 - Size of Array
10 - 1st element of Array
20 - 2nd element of Array
40 - 3rd element of Array
30 - 4th element of Array
60 - 5th element of Array
3 - we need to find the value of 3rd largest element
Here, the first input is 5, the size of array. 10, 20, 40, 30, 60 are the elements of array A[i]. The last input, i.e. 3, is pointing to the 3rd greatest element in the given array. Hence, the 3rd greatest element is 30
Java Solution
import java.util.Arrays;
import java.util.Scanner;
public class NthLargestNumber {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int turns = sc.nextInt();
int[] arr = new int[turns];
int index = 0;
while(turns > 0) {
arr[index++] = sc.nextInt();
turns--;
}
int nth = sc.nextInt();
Arrays.sort(arr);
boolean duplicateFound = false;
for(int i = 1; i < turns; i++) {
if(arr[i] == arr[i-1]) {
duplicateFound = true;
break;
}
}
if(duplicateFound) {
System.out.println("INVALID INPUT");
} else {
System.out.println(arr[arr.length-nth]);
}
}
}
For More TCS Digital Capability Assessment solution - Click here or Here
This Blog is Hard work !
Can you give me a treat 😌
0 Comments