Skip to content

Instantly share code, notes, and snippets.

@alex-r89
Last active January 31, 2021 18:20
Show Gist options
  • Save alex-r89/94129388730800d2fc83e71754ab9548 to your computer and use it in GitHub Desktop.
Save alex-r89/94129388730800d2fc83e71754ab9548 to your computer and use it in GitHub Desktop.
Hackerrank Solutions in JavaScript

Hackerrank Solutions

Easy

Array Matrix (Diagonal Difference)

Given a square matrix, calculate the absolute difference between the sums of its diagonals.

function diagonalDifference(arr) {
  // arr eg: [ [ 11, 2, 4 ], [ 4, 5, 6 ], [ 10, 8, -12 ] ]
    
    const arrLength = arr.length
    let leftDiagonal = 0, rightDiagonal = 0
    
    for(let i = 0; i < arrLength; i++){
        leftDiagonal += arr[i][i]
        rightDiagonal += arr[arrLength - 1 - i][i]
    }
    
     return Math.abs(leftDiagonal - rightDiagonal); 
}

Calculate ratio of positive, negative and zero values in an array (Plus Minus)

Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero.

function plusMinus(arr) {
    const total = arr.length
    let zeroCount = 0, positiveCount = 0, negativeCount = 0
    
    for(let i = 0; i < arr.length; i++){
      arr[i] < 0 ? negativeCount++ : arr[i] > 0 ? positiveCount++ : zeroCount++
    }
    console.log(eval(positiveCount/total))
    console.log(eval(negativeCount/total))
    console.log(eval(zeroCount/total))
    }

Create a tree using console log of # based on an input number (Staircase)

input: 4

expected output:

   #
  ##
 ###
####
function staircase(n) {
    let count = 0
    
    while(count < n){
        let hashArray = Array(count + 1).fill('#')
        console.log(' '.repeat(n - count -1) + hashArray.join(''))
        count++
    }
}

Count the frequency of the largest number in an array (Birthday Cake Candles)

input: [1,4,2,3,4]

expected output: 2

function birthdayCakeCandles(candles) {
    // **Simple ES6 Way**
    // const maxValue = Math.max(...candles)
    // const count = candles.filter(val => val == maxValue).length
    // return count
    
    // **Classic "algorithm challenge" way**
    // [1,2,3,4,4]
    let count = 0
    let maxValue = 0
    for(let i = 0; i < candles.length; i++){
        if(candles[i] == maxValue){
            count++
        }
        if(candles[i] > maxValue){
            maxValue = candles[i]
            count = 1
        }
    }
    
    return count
}

Convert 12 hour time string to 24 hour time string (Time Conversion)

input: 07:05:45PM expected output: 19:05:45

function timeConversion(s) {
const timeAsArray = s.slice(0,8).split(":")

timeAsArray[0] = (s.indexOf('PM') > -1) ? (timeAsArray[0] == 12 ? '12' : Number(timeAsArray[0]) + 12) : (timeAsArray[0] == 12 ? '00' : timeAsArray[0]);
    
    
    
return timeAsArray.join(':');

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment