Asked inNagarro,CSD
Second largest element in the array

You have been given an array/list 'ARR' of integers. Your task is to find the second largest element present in the 'ARR'.

Note:
a) Duplicate elements may be present.

b) If no such element is present return -1.
Example:
Input: Given a sequence of five numbers 2, 4, 5, 6, 8.

Output:  6

Explanation:
In the given sequence of numbers, number 8 is the largest element, followed by number 6 which is the second-largest element. Hence we return number 6 which is the second-largest element in the sequence.
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases. 

The next ‘2*T’ lines represent the ‘T’ test cases.

The first line of each test case contains an integer ‘N’ denoting the number of elements in the array.

The second line of each test case contains ‘N’ space-separated integers denoting the elements in the array. 
Output Format:
For each test case, print a single line containing a single integer denoting the second largest element in the array.

The output of each test case will be printed in a separate line.
Note:
You are not required to print the expected output; it has already been taken care of, Just implement the function.
Constraints:
1 <= T <= 100
1 <= N <= 5000
-10 ^ 9 <= 'SIZE' <= 10 ^ 9 

Where ‘T’ is the total number of test cases, ‘N’ denotes the number of elements in the array and ‘SIZE’ denotes the range of the elements in the array.

Time limit: 1 sec.
CodingNinjas
author
2y

1. Created an array
2. Find second largest element
3. Optimization

CodingNinjas
author
2y
Simple solution

The idea is to sort the array in decreasing order and return the second largest element in the array.

  1. Sort the array in decreasing order.
  2. We can create a function to sort the elements usi...read more
CodingNinjas
author
2y
A better approach

The approach is to traverse the array twice. In the first traversal find the maximum element of the array. In the second traversal find the greatest element less than the element obt...read more

CodingNinjas
author
2y
Efficient solution

The idea is to traverse the array once, check every element for the larger element, and store the previous largest element in a variable which will be our answer.

  • Initialize two vari...read more
Add answer anonymously...
Nagarro CSD Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter