Algorithm


Hacker rank Problem Name: 10 Days of JavaScript - Day 3: Arrays

Hacker rank Problem Link: https://www.hackerrank.com/challenges/js10-arrays/problem?isFullScreen=true

Objective

 

In this challenge, we learn about Arrays. Check out the attached tutorial for more details.

 

Function Description

 

Complete the getSecondLargest function in the editor below.

 

getSecondLargest has the following parameters:

 

  • int nums[n]: an array of integers

 

Returns

  • int: the second largest number in num8

Input Format

The first line contains an integer, n , the size of the num8 array.

The second line contains n space-separated numbers that describe the elements in num8 .

Constraints

  •  1 <= n <= 10
  •  0 <= num8i <= 10, where num8i is the number at index i.
  • The numbers in num8 may not be distinct.

    Sample Input 0

    5
    2 3 6 6 5
    

    Sample Output 0

    5
    

    Explanation 0

    Given the array num8 = [2, 3, 6, 6, 5], we see that the largest value in the array is 6 and the second largest value is 5. Thus, we return  5 as our answer.

 

 

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    
    main();    
});

function readLine() {
    return inputString[currentLine++];
}

function getSecondLargest(nums) {
    // Complete the function
    var sorted_array=nums.sort (function (a,b) {return a-b});
    var unique_sorted_array =sorted_array.filter(function(elem, index,  self)
    {
        return index==self.indexOf(elem);
    })
    return unique_sorted_array[unique_sorted_array.length - 2];
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
5 2 3 6 6 5

Output

x
+
cmd
5
Advertisements

Demonstration


Previous
[Solved] #2 Day 2: Loops in Javascript HackerRank - HackerRank Javascript in 10 days
Next
[Solved] #4 Day 4: Create a Rectangle Object in Javascript HackerRank - HackerRank Javascript in 10 days