Accenture Coding Question | Second Largest Number | CodeWindow

Second Largest

Given an array (containing at most 1000 positive integers), find the second largest integer. If there exists no second largest integer, return -1.

Input specification:
Input 1: Length of the array.
Input 2: an array of positive integers.

Output Specification:
Return the second largest number or -1 accordingly.

Example 1:
Input 1: 3
Input 2: {2,1,2}

Output: 1
Explanation:
1 is the second largest in the array.

Example 2:
Input 1: 5
Input 2: {4,7,9,8,0}

Output: 8
Explanation:
8 is the second largest in the array.

Solution in Python 3:

#https://codewindow.in
#join our telegram channel

l=int(input())
arr=list(map(int, input().split()))
arr=list(set(arr))
length_list=len(arr)

arr.sort()

#print("set = ",arr)
#print("length of set: ",length_list)

print(arr[length_list-2])

# Telegram @codewindow

Solution in C++ :

//https://codewindow.in
//join our telegram channel @codewindow

#include <bits/stdc++.h>
using namespace std;

void secondLargest(int arr[], int arr_size)
{
    int i, first, second;
    
    if (arr_size < 2) {
        printf(" Invalid Input ");
        return;
    }
    
    sort(arr, arr + arr_size);
    
    for (i = arr_size - 2; i >= 0; i--) {
        if (arr[i] != arr[arr_size - 1]) {
            printf("%d", arr[i]);
            return;
        }
    }
    printf("There is no second largest element\n");
}

int main()
{
    int n;
    cin >> n;
    int arr[n];
    for(int i=0;i<n;i++)
        cin >> arr[i];
    secondLargest(arr, n);
    return 0;
}

Solution in JAVA :

//https://codewindow.in
//join our telegram channel @codewindow

import java.util.*;

class CodeWindow {
    static void secondLargest(int arr[], int arr_size)
    {
        int i, first, second;
        if (arr_size < 2)
        {
            System.out.print("Invalid Input");
            return;
        }
        
        Arrays.sort(arr);
        for (i = arr_size - 2; i >= 0; i--)
        {
            if (arr[i] != arr[arr_size - 1])
            {
                System.out.print(arr[i]);
                return;
            }
      }
      System.out.print("There is no second largest element");
    }
 
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int arr[] = new int[n];
        for(int i=0;i<n;i++)
            arr[i] = sc.nextInt();
        secondLargest(arr, n);
    }
}

Output:

5
4 7 9 8 0
8
3
2 1 2
1
Recent Posts

Leave a Comment

Your email address will not be published. Required fields are marked *