Ninja And The Second Order Elements CodeStudio Java Solution

I can try to write the Ninja And The Second Order Elements problem for you. Here is one possible way to write it: Ninja And The Second Order Elements
Admin

Ninja And The Second Order Elements CodeStudio Java Solution

 

I can try to write the Ninja And The Second Order Elements problem for you. Here is one possible way to write it:

Ninja And The Second Order Elements

Ninja is a brilliant student in the class and hence his teacher assigned him a problem. He has been given an array `A` of `N` unique non-negative integers and has been asked to find the second largest and second smallest element from the array. Can you help him solve this problem?

Input Format:

The first line of input contains an integer `T`, denoting the number of test cases.The first line of each test case contains an integer `N`, denoting the size of the array.The second line of each test case contains `N` space-separated integers, denoting the elements of the array.

Output Format:

For each test case, print two space-separated integers, denoting the second largest and second smallest element from the array.

Constraints:

1 <= T <= 10

1 <= N <= 10^5

0 <= A[i] <= 10^9

A[i] != A[j] for i != j

Sample Input:

2

5

3 1 4 5 2

6

7 8 9 6 5 4

Sample Output:

4 2

8 5


Solution Java
public class Solution {
    public static int[] getSecondOrderElements(int n, int []a) {
        // Write your code here.
        int largest = a[0];
    for (int i = 1; i < n; i++) {
        if (a[i] > largest) {
            largest = a[i];
        }
    }
    
    int slargest = Integer.MIN_VALUE;
    for (int i = 0; i < n; i++) {
        if (a[i] < largest && a[i] > slargest) {
            slargest = a[i];
        }
    }
    
    int smallest = Integer.MAX_VALUE;
    int ssmallest = Integer.MAX_VALUE;
    for (int i = 0; i < n; i++) {
        if (a[i] < smallest) {
            smallest = a[i];
        }
    }
    for (int i = 0; i < n; i++) {
        if (a[i] != smallest && a[i] < ssmallest) {
            ssmallest = a[i];
        }
    }
    
    return new int[] {slargest, ssmallest};
    }
}

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.