Algorithm Problem Solving

Practice log used to track my progress with Javascript

Cut the Sticks

Source: HackerRank
Date Solved: Dec. 1, 2022
Problem:

You are given a number of sticks of varying lengths. You will iteratively cut the sticks into smaller sticks, discarding the shortest pieces until there are none left. At each iteration you will determine the length of the shortest stick remaining, cut that length from each of the longer sticks and then discard all the pieces of that shortest length. When all the remaining sticks are the same length, they cannot be shortened so discard them.
Given the lengths of n sticks, print the number of sticks that are left before each iteration until there are none left.

Example

arr = [1, 2, 3]
The shortest stick length is 1, so cut that length from the longer two and discard the pieces of length 1. Now the lengths are arr = [1, 2]. Again, the shortest stick is of length 1, so cut that amount from the longer stick and discard those pieces. There is only one stick left, arr = [1], so discard that stick. The number of sticks at each iteration are answer = [3, 2, 1].

Function Description

Complete the cutTheSticks function in the editor below. It should return an array of integers representing the number of sticks before each cut operation is performed.

cutTheSticks has the following parameter(s):

  • int arr[n]: the lengths of each stick
Returns
  • int[]: the number of sticks after each iteration
Input Format

The first line contains a single integer n, the size of arr.
The next line contains n space-separated integers, each an arr[i], where each value represents the length of the ith stick.

Constraints
  • 1 <= n <= 1000
  • 1 <= arr[i] <= 1000
Sample Input
                
STDIN           Function
-----           --------
6               arr[] size n = 6
5 4 4 2 2 8     arr = [5, 4, 4, 2, 2, 8]
                
            
Sample Output
                
6
4
2
1
                
            
Explanation
                
sticks-length        length-of-cut   sticks-cut
5 4 4 2 2 8             2               6
3 2 2 _ _ 6             2               4
1 _ _ _ _ 4             1               2
_ _ _ _ _ 3             3               1
_ _ _ _ _ _           DONE            DONE
                
            
My Solution:
                
function cutTheSticks(arr) {
    // Define empty array for holding the values the number of sticks that are left before each iteration until there are none left.
    let sticksCut = [];

    // Sort array least to greatest
    arr.sort(function(a, b) {
        return a - b;
        });
    
    for (let j = 0; j < arr.length; j++) {
        // Set sticks count to 0
        let sticks = 0;
    
        // Find the minimum value in the array; assign it to variable
        let minLength = arr.find(element => element > 0)
        
        // If no element is greater than 0; return the array
        if (minLength === undefined) {
            return sticksCut
        }
    
        for (let i = 0; i < arr.length; i++) {
            
            // Subtract minLength from index
            let newStickLength = arr[i] - minLength;
            
            // Remove value and replace with new stick length
            arr.splice(i, 1, newStickLength);
            
            // Count how many values are greater than 0 in the array 
            if (newStickLength >= 0) {
                sticks++;
            } 
    }
    
    // Push Count 
    sticksCut.push(sticks);

    }   return sticksCut;
}
                
            

Picking Numbers

Source: HackerRank
Date Solved: Oct. 25, 2022
Problem:

Given an array of integers, find the longest subarray where the absolute difference between any two elements is less than or equal to 1.

Example

a = [1, 1, 2, 2, 4, 4, 5, 5, 5]
There are two subarrays meeting the criterion: [1, 1, 2, 2] and [4, 4, 5, 5, 5]. The maximum length subarray has 5 elements.

Function Description

Complete the pickingNumbers function in the editor below.

pickingNumbers has the following parameter(s):

  • int a[n]: an array of integers
Returns
  • int: the length of the longest subarray that meets the criterion
Input Format

The first line contains a single integer n, the size of the array a.
The second line contains n space-separated integers, each an a[i].

Constraints
  • 2 <= n <= 100
  • 0 <= a[i] < 100
  • The answer will be >= 2.
Sample Input
                
6
4 6 5 3 3 1
                
            
Sample Output
                
3
                
            
Explanation

We choose the following multiset of integers from the array: {4, 3, 3}. Each pair in the multiset has an absolute difference <= 1 (i.e., |4 - 3| and |3 - 3| = 0), so we print the number of chosen integers, 3, as our answer.

My Solution:
                
function pickingNumbers(a) {
    a.sort();
    a.push(100);
    let subArrays = [];

    for (let i = 0; i < a.length; i++) {
        for (let j = i + 1; j < a.length; j++) {
            if (Math.abs(a[i] - a[j]) > 1) {
                let sub = a.slice(i, j);
                subArrays.push(sub);
                { break };
            }
        }
    } return Math.max(...subArrays.map(el => el.length));
}
                
            

Forming a Magic Square

Source: HackerRank
Date Solved: Oct. 21, 2022
Problem:

We define a magic square to be an n x n matrix of distinct positive integers from 1 to n2 where the sum of any row, column, or diagonal of length n is always equal to the same number: the magic constant.
You will be given a matrix 3 x 3 of integers in the inclusive range [1, 9]. We can convert any digit a to any other digit b in the range [1, 9] at cost of |a - b|. Given s, convert it into a magic square at minimal cost. Print this cost on a new line.
Note: The resulting magic square must contain distinct integers in the inclusive range [1, 9].

Example

$s = [[5, 3, 4], [1, 5, 8], [6, 4, 2]]
The matrix looks like this:

                
5 3 4
1 5 8
6 4 2
                
            

We can convert it to the following magic square:

                
8 3 4
1 5 9
6 7 2
                
            

This took three replacements at a cost of |5 - 8| + |8 - 9| + |4 -7| = 7.

Function Description

Complete the formingMagicSquare function in the editor below.

formingMagicSquare has the following parameter(s):

  • int s[3][3]: a 3 x 3 array of integers
Returns
  • int: the minimal total cost of converting the input square to a magic square
Input Format

Each of the 3 lines contains three space-separated integers of row s[i].

Constraints
  • s[i][j] ∈ [1, 9]
Sample Input
                
4 9 2
3 5 7
8 1 5
                
            
Sample Output
                
1
                
            
Explanation

If we change the bottom right value, s[2][2], from 5 to 6 at a cost of |6 - 5| = 1, s becomes a magic square at the minimum possible cost.

My Solution:
                

                
            

Cats and a Mouse

Source: HackerRank
Date Solved: Oct. 20, 2022
Problem:

Two cats and a mouse are at various positions on a line. You will be given their starting positions. Your task is to determine which cat will reach the mouse first, assuming the mouse does not move and the cats travel at equal speed. If the cats arrive at the same time, the mouse will be allowed to move and it will escape while they fight.
You are given q queries in the form of x, y, and z representing the respective positions for cats A and B, and for mouse C. Complete the function catAndMouse to return the appropriate answer to each query, which will be printed on a new line.

  • If cat A catches the mouse first, print Cat A.
  • If cat B catches the mouse first, print Cat B.
  • If both cats reach the mouse at the same time, print Mouse C as the two cats fight and mouse escapes.
Example

x = 2
y = 5
z = 4
The cats are at positions 2 (Cat A) and 5 (Cat B), and the mouse is at position 4. Cat B, at position 5 will arrive first since it is only 1 unit away while the other is 2 units away. Return 'Cat B'.

Function Description

Complete the catAndMouse function in the editor below.
catAndMouse has the following parameter(s):

  • int x: Cat A's position
  • int y: Cat B's position
  • int z: Mouse C's position
Returns
  • string: Either 'Cat A', 'Cat B', or 'Mouse C'
Input Format

The first line contains a single integer, q, denoting the number of queries.
Each of the q subsequent lines contains three space-separated integers describing the respective values of x (cat A's location), y (cat B's location), and z (mouse C's location).

Constraints
  • 1 <= q <= 100
  • 1 <= x, y, z <= 100
Sample Input
                
2
1 2 3
1 3 2
                
            
Sample Output
                
Cat B
Mouse C
                
            
Explanation

Query 0: The positions of the cats and mouse are shown below:

Cat and Mouse

Cat B will catch the mouse first, so we print Cat B on a new line.
Query 1: In this query, cats A and B reach mouse C at the exact same time:

Cat and Mouse

Because the mouse escapes, we print Mouse C on a new line.

My Solution:
                
function catAndMouse(x, y, z) {
    let catA = Math.abs(z - x);
    let catB = Math.abs(z - y);

    if (catA === catB) {
        return "Mouse C";
    } else if (catA < catB) {
        return "Cat A";
    } return "Cat B";
}
                
            

Electronics Shop

Source: HackerRank
Date Solved: Oct. 19, 2022
Problem:

A person wants to determine the most expensive computer keyboard and USB drive that can be purchased with a given budget. Given price lists for keyboards and USB drives and a budget, find the cost to buy them. If it is not possible to buy both items, return -1.

Example

b = 60
keyboards = [40, 50, 60]
drives = [5, 8, 12] The person can buy a 40 keyboard + 12 USB drive = 52, or a 50 keyboard + 8 USB drive = 58. Choose the latter as the more expensive option and return 58.

Function Description

Complete the getMoneySpent function in the editor below.

getMoneySpent has the following parameter(s):

  • int keyboards[n]: the keyboard prices
  • int drives[m]: the drive prices
  • int b: the budget
Returns
  • int: the maximum that can be spent, or -1 if it is not possible to buy both items
Input Format

The first line contains three space-separated integers b, n, and m, the budget, the number of keyboard models and the number of USB drive models.
The second line contains n space-separated integers keyboard[i], the prices of each keyboard model.
The third line contains m space-separated integers drives, the prices of the USB drives.

Constraints
  • 1 <= n, m <= 1000
  • 1 <= b <= 106
  • The price of each item is in the inclusive range [1, 106]
Sample Input
                
10 2 3
3 1
5 2 8
                
            
Sample Output
                
9
                
            
Explanation

Buy the 2nd keyboard and the 3rd USB drive for a total cost of 8 + 1 = 9.

My Solution:
                
function getMoneySpent(keyboards, drives, b) {

    let total = [];
    
    for (let i = 0; i < keyboards.length; i++) {
        for (let j = 0; j < drives.length; j++) {
            let sum = keyboards[i] + drives[j];
            
            if (sum <= b) {
                total.push(sum);
            }
        }
    } 
    
    if (!total.length){
        return -1;
    } total = total.sort((a,b) => a-b)
        return total[total.length-1]
}
                
            

Counting Valleys

Source: HackerRank
Date Solved: Oct. 18, 2022
Problem:

An avid hiker keeps meticulous records of their hikes. During the last hike that took exactly steps steps, for every step it was noted if it was an uphill, U, or a downhill, D step. Hikes always start and end at sea level, and each step up or down represents a 1 unit change in altitude. We define the following terms:

  • A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
  • A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.

Given the sequence of up and down steps during a hike, find and print the number of valleys walked through.

Example

steps = 8 path = [DDUUUUDD]
The hiker first enters a valley 2 units deep. Then they climb out and up onto a mountain 2 units high. Finally, the hiker returns to sea level and ends the hike.

Function Description

Complete the countingValleys function in the editor below.

countingValleys has the following parameter(s):

  • int steps: the number of steps on the hike
  • string path: a string describing the path
Returns
  • int: the number of valleys traversed
Input Format

The first line contains an integer steps, the number of steps in the hike.
The second line contains a single string path, of steps characters that describe the path.

Constraints
  • 2 <= steps <= 106
Sample Input
                
8
UDDDUDUU
                
            
Sample Output
                
1
                
            
Explanation

If we represent _ as sea level, a step up as /, and a step down as \, the hike can be drawn as:

                
 _/\       _
    \    /
     \/\/
                
            

The hiker enters and leaves one valley.

My Solution:
                
function countingValleys(steps, path) {
    let seaLevel = 0;
    let valleys = 0;
    
    let arPath = path.split("")
    
    for (let i = 0; i < arPath.length; i++) {
        if (arPath[i] === "D" ) {
            seaLevel--;
            arPath.splice(i, 1, seaLevel);
        } else {
            seaLevel++;
            arPath.splice(i, 1, seaLevel);
        } 
        
        if (arPath[i] === 0 && arPath[i-1] === -1) {
                valleys++
            }
    } return valleys
}
                
            

Drawing Book

Source: HackerRank
Date Solved: Oct. 17, 2022
Problem:

A teacher asks the class to open their books to a page number. A student can either start turning pages from the front of the book or from the back of the book. They always turn pages one at a time. When they open the book, page 1 is always on the right side:

page 1

When they flip page 1, they see pages 2 and 3. Each page except the last page will always be printed on both sides. The last page may only be printed on the front, given the length of the book. If the book is n pages long, and a student wants to turn to page p, what is the minimum number of pages to turn? They can start at the beginning or the end of the book.
Given n and p, find and print the minimum number of pages that must be turned in order to arrive at page p.

Example

n = 5
p = 3

drawingbook 2

Using the diagram above, if the student wants to get to page 3, they open the book to page 1, flip 1 page and they are on the correct page. If they open the book to the last page, page 5, they turn 1 page and are at the correct page. Return 1.

Function Description

Complete the pageCount function in the editor below.

pageCount has the following parameter(s):

  • int n: the number of pages in the book
  • int p: the page number to turn to
Returns
  • int: the minimum number of pages to turn
Input Format

The first line contains an integer n, the number of pages in the book.
The second line contains an integer, p, the page to turn to.

Constraints
  • 1 <= n <= 105
  • 1 <= p <= n
Sample Input
                
6
2
                
            
Sample Output
                
1
                
            
Explanation

If the student starts turning from page 1 , they only need to turn 1 page:

drawingbook 3

If a student starts turning from page 6, they need to turn 2 pages:

drawingbook 4

Return the minimum value, 1.

My Solution:
                
function pageCount(n, p) {

    let fromFront = Math.floor(p/2);
    let fromBack = 0;
    
    if ((n%2 === 0) && (p%2 !== 0)) {
        fromBack = Math.ceil((n - p) / 2)
    } else {
        fromBack = Math.floor((n - p) / 2)
    }
    
    if (fromFront <= fromBack) {
        return fromFront
    }   return fromBack
}
                
            

Sales by Match

Source: HackerRank
Date Solved: Oct. 15, 2022
Problem:

There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

Example

n = 7
ar = [1, 2, 1, 2, 1, 3, 2]
There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2.

Function Description

Complete the sockMerchant function in the editor below.

sockMerchant has the following parameter(s):

  • int n: the number of socks in the pile
  • int ar[n]: the colors of each sock
Returns
  • int: the number of pairs
Input Format

The first line contains an integer n, the number of socks represented in ar.
The second line contains n space-separated integers, ar[i], the colors of the socks in the pile.

Constraints
  • 1 <= n <= 100
  • 1 <= ar[i] <= 100 where 0 <= i < n
Sample Input
                
STDIN                       Function
-----                       --------
9                           n = 9
10 20 20 10 10 30 50 10 20  ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]
                
            
Sample Output
                
3
                
            
Explanation
pairs

There are three pairs of socks.

My Solution:
                
function sockMerchant(n, ar) {
    let pairs = 0;
    
    for (let i = 0; i < ar.length; i++) {
        for (let j = i + 1; j < ar.length; j++){
            if (ar[i] === ar[j]) {
                pairs++;
                ar.splice(i, 1, "");
                ar.splice(j, 1);
            }
        } 
    } return pairs
}
                
            

Bill Division

Source: HackerRank
Date Solved: Oct 14, 2022
Problem:

Two friends Anna and Brian, are deciding how to split the bill at a dinner. Each will only pay for the items they consume. Brian gets the check and calculates Anna's portion. You must determine if his calculation is correct.
For example, assume the bill has the following prices: bill = [2, 4, 6]. Anna declines to eat item k = bill[2] which costs 6. If Brian calculates the bill correctly, Anna will pay (2 + 4)/2 = 3. If he includes the cost of bill[2], he will calculate (2 + 4 + 6)/2 = 6. In the second case, he should refund 3 to Anna.

Function Description

Complete the bonAppetit function in the editor below. It should print Bon Appetit if the bill is fairly split. Otherwise, it should print the integer amount of money that Brian owes Anna.

bonAppetit has the following parameter(s):

  • bill: an array of integers representing the cost of each item ordered
  • k: an integer representing the zero-based index of the item Anna doesn't eat
  • b: the amount of money that Anna contributed to the bill
Input Format

The first line contains two space-separated integers n and k, the number of items ordered and the 0-based index of the item that Anna did not eat.
The second line contains n space-separated integers bill[i] where 0 <= i < n.
The third line contains an integer, b, the amount of money that Brian charged Anna for her share of the bill.

Constraints
  • 2 <= n <= 105
  • 0 <= k <= n
  • 0 <= bill[i] <= 104
  • The amount of money due Anna will always be an integer
Sample Input
                
4 1
3 10 2 9
12   
                
            
Sample Output
                
5  
                
            
Explanation

Anna didn't eat item bill[1] = 10, but she shared the rest of the items with Brian. The total cost of the shared items is 3 + 2 + 9 = 14 and, split in half, the cost per person is bactual. Brian charged her bcharged = 12 for her portion of the bill. We print the amount Anna was overcharged, bcharged - bactual = 12 - 7 = 5, on a new line.

My Solution:
                
function bonAppetit(bill, k, b) {
    bill.splice(k, 1);
    
    let bActual = bill.reduce((a, b) => a + b, 0) / 2;
    
    if (b !== bActual) {
        console.log (b - bActual);
    } else {
        console.log ("Bon Appetit");
    }
}
                
            

Day of the Programmer

Source: HackerRank
Date Solved: Oct. 13, 2022
Problem:

Marie invented a Time Machine and wants to test it by time-traveling to visit Russia on the Day of the Programmer (the 256th day of the year) during a year in the inclusive range from 1700 to 2700.

From 1700 to 1917, Russia's official calendar was the Julian calendar; since 1919 they used the Gregorian calendar system. The transition from the Julian to Gregorian calendar system occurred in 1918, when the next day after January 31st was February 14th. This means that in 1918, February 14th was the 32nd day of the year in Russia.

In both calendar systems, February is the only month with a variable amount of days; it has 29 days during a leap year, and 28 days during all other years. In the Julian calendar, leap years are divisible by 4; in the Gregorian calendar, leap years are either of the following:

  • Divisible by 400.
  • Divisible by 4 and not divisible by 100.

Given a year, y, find the date of the 256th day of that year according to the official Russian calendar during that year. Then print it in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is y.

For example, the given year = 1984. 1984 is divisible by 4, so it is a leap year. The 256th day of a leap year after 1918 is September 12, so the answer is 12.09.1984.

Function Description

Complete the dayOfProgrammer function in the editor below. It should return a string representing the date of the 256th day of the year given.

dayOfProgrammer has the following parameter(s):

  • year: an integer
Input Format

A single integer denoting year y.

Constraints
  • 1700 \le y \le 2700
Output Format
Print the full date of Day of the Programmer during year y in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is y.

My Solution:
                
function dayOfProgrammer(year) {
    if ((year > 1918) && ((year % 400 === 0) || (year % 4 === 0 && year % 100 !== 0))) {
        return ('12.09.' + year);
    } else if ((year < 1918) && (year % 4 === 0)) {
        return ('12.09.' + year);
    } else if (year === 1918) {
        return ('26.09.' + year);
    } else {
        return ('13.09.' + year);
    }
}
                
            

Migratory Birds

Source: HackerRank
Date Solved: Oct. 12, 2022
Problem:

Given an array of bird sightings where every element represents a bird type id, determine the id of the most frequently sighted type. If more than 1 type has been spotted that maximum amount, return the smallest of their ids.

Example
arr = [1, 1, 2, 2, 3]

There are two each of types 1 and 2, and one sighting of type 3. Pick the lower of the two types seen twice: type 1.

Function Description

Complete the migratoryBirds function in the editor below.

migratoryBirds has the following parameter(s):

  • int arr[n]: the types of birds sighted
Returns
  • int: the lowest type id of the most frequently sighted birds
Input Format

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

The second line describes arr as n space-separated integers, each a type number of the bird sighted.

Constraints

It is guaranteed that each type is 1, 2, 3, 4, or 5.

My Solution:
                
function migratoryBirds(arr) {
    let count1 = 0;
    let count2 = 0;
    let count3 = 0;
    let count4 = 0;
    let count5 = 0;
    
    let repeats = [];
    
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === 1) {
            count1++; 
        } else if (arr[i] === 2) {
            count2++; 
        } else if (arr[i] === 3) {
            count3++; 
        } else if (arr[i] === 4) {
            count4++; 
        } else if (arr[i] === 5) {
            count5++; 
        }
    } 
    repeats.push(count1, count2, count3, count4, count5)
    return repeats.indexOf(Math.max(...repeats)) + 1
}
                
            

Divisible Sum Pairs

Source: HackerRank
Date Solved: Oct. 11, 2022
Problem:

Given an array of integers and a positive integer k , determine the number of (i, j) pairs where i < j and ar[i] + ar[j] is divisible by k.

Example

ar = [1, 2, 3, 4, 5, 6]

k = 5

Three pairs meet the criteria: [1, 4], [2, 3], and [4, 6].

Function Description

Complete the divisibleSumPairs function in the editor below.

divisibleSumPairs has the following parameter(s):

  • int n: the length of array ar
  • int ar[n]: an array of integers
  • int k: the integer divisor
Returns
  • int: the number of pairs
Input Format

The first line contains 2 space-separated integers, n and k.

The second line contains n space-separated integers, each a value of arr[i].

Constraints
  • 2 <= n <= 100
  • 1 <= k <= 100
  • 1 <= ar[i] <= 100
Sample Input

6 3

1 3 2 6 1 2

Sample Output

5

Explanation

Here are the 5 valid pairs when k=3:

  • (0, 2) --> ar[0] + ar[2] = 1 + 2 = 3
  • (0, 5) --> ar[0] + ar[5] = 1 + 2 = 3
  • (1, 3) --> ar[1] + ar[3] = 3 + 6 = 9
  • (2, 4) --> ar[2] + ar[4] = 2 + 1 = 3
  • (4, 5) --> ar[4] + ar[5] = 1 + 2 = 3
My Solution:
                
function divisibleSumPairs(n, k, ar) {
    let count = 0; 
    
    for (let i = 0; i < ar.length; i++) {
        for (let j = (i+1); j < ar.length; j++) {
                let sum = ar[i] + ar [j];
                
                if ((sum % k) === 0) {
                    count++;
                }
        } 
    } return count;
}
                    
                
            

Subarray Division

Source: HackerRank
Date Solved: Oct. 10, 2022
Problem:

Two children, Lily and Ron, want to share a chocolate bar. Each of the squares has an integer on it.

Lily decides to share a contiguous segment of the bar selected such that:

  • The length of the segment matches Ron's birth month, and,
  • The sum of the integers on the squares is equal to his birth day.

Determine how many ways she can divide the chocolate.

Example

s = [2, 2, 1, 3, 2]

d = 4

m = 2

Lily wants to find segments summing to Ron's birth day, d = 4 with a length equalling his birth month, m = 2. In this case, there are two segments meeting her criteria: [2, 2] and [1, 3].

Function Description

Complete the birthday function.

birthday has the following parameter(s):

int s[n]: the numbers on each of the squares of chocolate

int d: Ron's birth day

int m: Ron's birth month

Returns

int: the number of ways the bar can be divided

My Solution:
                
function birthday(s, d, m) {
                            
    function reducer(previousValue, currentValue, index) {
        const returns = previousValue + currentValue;
        return returns;
    }

    let count = 0;

    for (let i = 0; i < s.length; i++) {
        let removed = s.slice(i, (i+m));
        let sum = removed.reduce(reducer);
    
        if (sum === d) {
            count++;
        }

    } return count;
}
                        
                    

Breaking the Records

Source: HackerRank
Date Solved: Oct. 6, 2022
Problem:

Maria plays college basketball and wants to go pro. Each season she maintains a record of her play. She tabulates the number of times she breaks her season record for most points and least points in a game. Points scored in the first game establish her record for the season, and she begins counting from there.

Example

scores = [12, 24, 10, 24]

Scores are in the same order as the games played. She tabulates her results as follows:

Game Score Minimum Maximum Count-Min Count-Max
0 12 12 12 0 0
1 24 12 24 0 1
2 10 10 24 1 1
3 24 10 24 1 1

Given the scores for a season, determine the number of times Maria breaks her records for most and least points scored during the season.

Function Description

Complete the breakingRecords function in the editor below.

breakingRecords has the following parameter(s):

  • int scores[n]: points scored per game
Returns
  • int[2]: An array with the numbers of times she broke her records. Index 0 is for breaking most points records, and index 1 is for breaking least points records.
Input Format

The first line contains an integer n, the number of games.

The second line contains n space-separated integers describing the respective values of score0, score1,...,scoren-1.

Constraints
  • 1 <= n <= 1000
  • 0 <= scores[i] <= 108
Sample Input

9

10 5 20 20 4 5 2 25 1

Sample Output

2 4

Explanation

The diagram below depicts the number of times Maria broke her best and worst records throughout the season:

She broke her best record twice (after games 2 and 7 ) and her worst record four times (after games 1, 4, 6, and 8), so we print 2 4 as our answer. Note that she did not break her record for best score during game 3, as her score during that game was not strictly greater than her best record at the time.

My Solution:
                
function breakingRecords(scores) {
    let records = [scores[0], scores[0]];
    let maxcount = 0;
    let mincount = 0;
    let countArr = [0, 0];

    for (let i = 0; i < scores.length; i++) {
        if (scores[i] > records[0]) {
            records.splice(0, 1, scores[i]);
            maxcount++;
        } else if (scores[i] < records[1]) {
            records.splice(1, 1, scores[i]);
            mincount++;
        }
    }
    countArr.splice(0, 1, maxcount);
    countArr.splice(1, 1, mincount);
    return countArr
}
                
            

Between Two Sets

Source: HackerRank
Date Solved: Oct. 5, 2022
Problem:

There will be two arrays of integers. Determine all integers that satisfy the following two conditions:

  1. The elements of the first array are all factors of the integer being considered
  2. The integer being considered is a factor of all elements of the second array

These numbers are referred to as being between the two arrays. Determine how many such numbers exist.

Example

a = [2, 6]

b = [24, 36]

There are two numbers between the arrays: 6 and 12.

6%2=0, 6%6=0, 24%6=0 and 36%6=0 for the first value.

12%2=0, 12%6=0 and 24%12=0, 36%12=0 for the second value. Return 2.

Function Description

Complete the getTotalX function in the editor below. It should return the number of integers that are betwen the sets.

getTotalX has the following parameter(s):

  • int a[n]: an array of integers
  • int b[m]: an array of integers
Returns
  • int: the number of integers that are between the sets
Input Format

The first line contains two space-separated integers, n and m, the number of elements in arrays a and b.

The second line contains n distinct space-separated integers a[i] where 0 <= i < n.

The third line contains m distinct space-separated integers b[j] where 0 <= j < m.

Constraints
  • 1 <= n, m <= 10
  • 1 <= a[i] <= 100
  • 1 <= b[j] <= 100

My Solution:
                
function getTotalX(a, b) {
    let rangeArr = [];
    let maxA = Math.max(...a);
    let counter = 0

    for (let i = 1; i <= 100; i ++) {
        let r = maxA * i;
        rangeArr.push(r);
        if (r === b[0]) {
            { break }
        } 
    }
    
    for (let k = 0; k < rangeArr.length; k++) {
        for (let j = 0; j < b.length; j++){
            let remainder = b[j] % rangeArr[k]
            
            if (remainder !== 0) {
                rangeArr.splice(k, 1, 0)
                { break }
            } 
        } 

        for (let g = 0; g < a.length; g++){
            let remainder = rangeArr[k] % a[g];
            
            if (remainder !== 0) {
                rangeArr.splice(k, 1, 0)
                { break }
            } 
        }
    } 
    
    for (let t= 0; t < rangeArr.length; t++) {
            if (rangeArr[t] !== 0) {
                counter++;
            }
        } return counter;
}
                
            

Number Line Jumps

Source: HackerRank
Date Solved: Oct 4, 2022
Problem:

You are choreographing a circus show with various animals. For one act, you are given two kangaroos on a number line ready to jump in the positive direction (i.e, toward positive infinity).

  • The first kangaroo starts at location x1 and moves at a rate of v1 meters per jump.
  • The second kangaroo starts at location x2 and moves at a rate of v2 meters per jump.

You have to figure out a way to get both kangaroos at the same location at the same time as part of the show. If it is possible, return YES, otherwise return NO.

Example

x1 = 2
v1 = 1
x2 = 1
v2 = 2
After one jump, they are both at x = 3 , (x1 + v1 = 2 + 1, x2 +v2 = 1 + 2), so the answer is YES.

Function Description

Complete the function kangaroo in the editor below.

kangaroo has the following parameter(s):

  • int x1, int v1: starting position and jump distance for kangaroo 1
  • int x2, int v2: starting position and jump distance for kangaroo 2
Returns
  • string: either YES or NO
Input Format

A single line of four space-separated integers denoting the respective values of x1, v1, x2, and v2.

Constraints
  • 0 <= x1 < x2 <= 10000
  • 1 <= v1 <= 10000
  • 1 <= v2 <= 10000
Sample Input
                
0 3 4 2
                
            
Sample Output
                
YES
                
            
Explanation

The two kangaroos jump through the following sequence of locations:

number line jumps

From the image, it is clear that the kangaroos meet at the same location (number 12 on the number line) after same number of jumps (4 jumps), and we print YES.

My Solution:
                
function kangaroo(x1, v1, x2, v2) {

    for (let i = 0; i <= 10000; i++) {
        x1 += v1;
        x2 += v2;      
        if (x1 === x2) {
            return "YES";
        }  
    } return "NO"   
}
                
            

Apple and Orange

Source: HackerRank
Date Solved: Oct. 3, 2022
Problem:

Sam's house has an apple tree and an orange tree that yield an abundance of fruit. Using the information given below, determine the number of apples and oranges that land on Sam's house.

In the diagram below:

  • The red region denotes the house, where s is the start point, and t is the endpoint. The apple tree is to the left of the house, and the orange tree is to its right.
  • Assume the trees are located on a single point, where the apple tree is at point a, and the orange tree is at point b.
  • When a fruit falls from its tree, it lands d units of distance from its tree of origin along the x-axis. *A negative value of d means the fruit fell d units to the tree's left, and a positive value of d means it falls d units to the tree's right. *
apple and orange tree

Given the value of d for m apples and n oranges, determine how many apples and oranges will fall on Sam's house (i.e., in the inclusive range [s,t])?

For example, Sam's house is between s=7 and t=10. The apple tree is located at a=4 and the orange at b=12. There are m=3 apples and n=3 oranges. Apples are thrown apples = [2, 3, -4] units distance from a, and oranges = [3, -2, -4] units distance. Adding each apple distance to the position of the tree, they land at [4+2, 4+3, 4+-4] = [6, 7, 0]. Oranges land at [12+3, 12+-2, 12+-4] = [15, 10, 8]. One apple and two oranges land in the inclusive range 7 - 10 so we print

                    
1
2
                    
                
Function Description

Complete the countApplesAndOranges function in the editor below. It should print the number of apples and oranges that land on Sam's house, each on a separate line.

countApplesAndOranges has the following parameter(s):

  • s: integer, starting point of Sam's house location.
  • t: integer, ending location of Sam's house location.
  • a: integer, location of the Apple tree.
  • b: integer, location of the Orange tree.
  • apples: integer array, distances at which each apple falls from the tree.
  • oranges: integer array, distances at which each orange falls from the tree.
Input Format

The first line contains two space-separated integers denoting the respective values of s and t.
The second line contains two space-separated integers denoting the respective values of a and b.
The third line contains two space-separated integers denoting the respective values of m and n.
The fourth line contains m space-separated integers denoting the respective distances that each apple falls from point a.
The fifth line contains n space-separated integers denoting the respective distances that each orange falls from point b.

Constraints
  • 1 <= s, t, a, b, m, n <= 105
  • -105 <= d <= 105
  • a < s < t < b
Output Format

Print two integers on two different lines:

  1. The first integer: the number of apples that fall on Sam's house.
  2. The second integer: the number of oranges that fall on Sam's house.
Sample Input
                
7 11
5 15
3 2
-2 2 1
5 -6
                
            
Sample Output
                
1
1
                
            
Explanation

The first apple falls at position 5 - 2 = 3.
The second apple falls at position 5 + 2 = 7.
The third apple falls at position 5 + 1 = 6.
The first orange falls at position 15 + 5 = 20.
The second orange falls at position 15 - 6 = 9.
Only one fruit (the second apple) falls within the region between 7 and 11, so we print 1 as our first line of output.
Only the second orange falls within the region between 7 and 11, so we print 1 as our second line of output.

My Solution:
                
function countApplesAndOranges(s, t, a, b, apples, oranges) {
    let appleCount = 0;
    let orangeCount = 0;
    
    for (let i = 0; i < apples.length; i++) {
        let fallenApple = apples[i] + a;
            if ((fallenApple >= s) && (fallenApple <= t)) {
                appleCount++;
            } 
    } console.log(appleCount);
    
    for (let j = 0; j < oranges.length; j++) {
        let fallenOrange = oranges[j] + b;
        if ((fallenOrange >= s) && (fallenOrange <= t)) {
                orangeCount++;
            } 
    } console.log(orangeCount);   
}
                
            

Grading Students

Source: HackerRank
Date Solved: Oct. 3, 2022
Problem:

HackerLand University has the following grading policy:

  • Every student receives a grade in the inclusive range from 0 to 100.
  • Any grade less than 40 is a failing grade.

Sam is a professor at the university and likes to round each student's grade according to these rules:

  • If the difference between the grade and the next multiple of 5 is less than 3, round grade up to the next multiple of 5.
  • If the value of grade is less than 38, no rounding occurs as the result will still be a failing grade.
Example
  • grade = 84 round to 85 (85 - 84 is less than 3)
  • grade = 29 do not round (result is less than 40)
  • grade = 57 do not round (60 - 57 is 3 or higher)

Given the initial value of grade for each of Sam's n students, write code to automate the rounding process.

Function Description

Complete the function gradingStudents in the editor below.

gradingStudents has the following parameter(s):

  • int grades[n]: the grades before rounding
Returns
  • int[n]: the grades after rounding as appropriate
Input Format

The first line contains a single integer, n, the number of students.

Each line i of the n subsequent lines contains a single integer, grades[i].

Constraints
  • 1 <= n <= 60
  • 0 <= grades[i] <= 100
Sample Input

4
73
67
38
33

Sample Output

75
67
40
33

Explanation
results table
  1. Student 1 received a 73, and the next multiple of 5 from 73 is 75. Since 75 - 73 < 3, the student's grade is rounded to 75.
  2. Student 2 received a 67, and the next multiple of 5 from 67 is 70. Since 70 - 67 = 3, the grade will not be modified and the student's final grade is 67.
  3. Student 3 received a 38, and the next multiple of 5 from 38 is 40. Since 40 - 38 < 3, the student's grade will be rounded to 40.
  4. Student 4 received a grade below 33, so the grade will not be modified and the student's final grade is 33.
My Solution:
                
function gradingStudents(grades) {
    let finalGrades = [];
    let n = grades.length;
    
    for (let i = 0; i < n; i++) {
        let roundUp = Math.ceil(grades[i]/5)*5;

        if ((grades[i] < 38) || (grades[i] >= 38 && ((roundUp - grades[i]) >= 3))) {
            finalGrades.push(grades[i]);
        } else if (grades[i] >= 38 && ((roundUp - grades[i]) < 3)) {
            finalGrades.push(roundUp);
        } 
    } return finalGrades
}
                
            

Time Conversion

Source: HackerRank
Date Solved: Oct. 3, 2022
Problem:

Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.

Note:

  • 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.
  • 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.
Example
  • s = '12:01:00PM'

Return '12:01:00'.

  • s = '12:01:00AM'

Return '00:01:00'.

Function Description

Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format.

timeConversion has the following parameter(s):

  • string s: a time in 12 hour format
Returns
  • string: the time in 24 hour format
Input Format

A single string s that represents a time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM).

Constraints
  • All input times are valid
Sample Input

07:05:45PM

Sample Output

19:05:45

My Solution:
                
function timeConversion(s) {
    let hh = s.slice(0, 2);
    let intHH = parseInt(hh);
    let ampm = s.slice(8);
    let militaryTime = '';
    if ((ampm === 'PM' && hh === '12') || (ampm === 'AM' && hh !== '12')) {
        militaryTime = s.slice(0, 8);
    }
    else if (ampm === 'AM' && hh === '12') {
        militaryTime = s.replace('12', '00').slice(0, 8);
    }
    else if (ampm === 'PM' && hh !== '12') {
        intHH += 12;
        let updatedTime = s.replace(hh, intHH);
        militaryTime = updatedTime.slice(0, 8)
    } return militaryTime
}
                
            

Birthday Cake Candles

Source: HackerRank
Date Solved: Oct. 1, 2022
Problem:

You are in charge of the cake for a child's birthday. You have decided the cake will have one candle for each year of their total age. They will only be able to blow out the tallest of the candles. Count how many candles are tallest.

Example

candles = [4, 4, 1, 3]

The maximum height candles are 4 units high. There are 2 of them, so return 2.

Function Description

Complete the function birthdayCakeCandles in the editor below.

birthdayCakeCandles has the following parameter(s):

  • int candles[n]: the candle heights
Returns
  • int: the number of candles that are tallest
Input Format

The first line contains a single integer, n, the size of candles[].

The second line contains n space-separated integers, where each integer i describes the height of candles[i].

Constraints
  • 1 <= n <= 105
  • 1 <= candles[i] <= 107
Sample Input

4

3 2 1 3

Sample Output

2

Explanation

Candle heights are [3, 2, 1, 3]. The tallest candles are 3 units, and there are 2 of them.

My Solution:
                
function birthdayCakeCandles(candles) {
    candles.sort(function(a,b){return a-b});
    let n = candles.length;
    let highest = candles[n-1]; 

    let highestCount = 0
    
    for (let i = 0; i < n; i++) {
        if (candles[i] === highest) {
            highestCount ++
        }
    }   return highestCount
}
                
            

Mini-Max Sum

Source: HackerRank
Date Solved: Oct. 1, 2022
Problem:

Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.

Example:

arr = [1,3,5,7,9]

The minimum sum is: 1 + 3 + 5 + 7 = 16

The maximum sum is: 3 + 5 + 7 + 9 = 24 .

The function prints: 16 24 .

My Solution:
                        
function miniMaxSum(arr) {

    function compareNumbers(a, b) {
        return a - b;
    }
    
    let joined = arr.join()
    let sortedArr = arr.sort(compareNumbers);
    
    let maxSum = 0; 
    let minSum = 0;
    
    for (let i = 1; i < arr.length; i++) {
        maxSum+= arr[i]
    }
    
    for (let i = 0; i < arr.length-1; i++) {
        minSum+= arr[i]
    }
    
    console.log(minSum, maxSum);
} 
                        
                    

The Staircase

Source: HackerRank
Date Solved: Sept. 29, 2022
Problem:

This is a staircase of size n = 4:

                        
   #
  ##
 ###
####
                        
                    

Its base and height are both equal to n. It is drawn using # symbols and spaces. The last line is not preceded by any spaces. Write a program that prints a staircase of size n.

My Solution:
                        
function staircase(n) {
    for (let i = 1; i <= n; i++){
        console.log((' '.repeat(n-i)) + '#'.repeat(i));
    };
                        
                    

Plus Minus

Source: HackerRank
Date Solved: Sept. 27, 2022
Problem:

Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with 6 places after the decimal.

Print the ratios of positive, negative and zero values in the array. Each value should be printed on a separate line with 6 digits after the decimal. The function should not return a value.

Input Format

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

The second line contains n space-separated integers that describe arr[n].

Sample Input
                
STDIN           Function
-----           --------
6               arr[] size n = 6
-4 3 -9 0 4 1   arr = [-4, 3, -9, 0, 4, 1]
                
            
Sample Output
                
0.500000
0.333333
0.166667
                
            
Explanation

There are 3 positive numbers, 2 negative numbers, and 1 zero in the array. The proportions of occurrence are:

positive: (3/6) = 0.500000,

negative: (2/6) = 0.333333

zeros: (1/6) = 0.166667.

My Solution:
                                
function plusMinus(arr) {
let positive = 0;
let negative = 0;
let zero = 0;
let n = arr.length;

for (let i = 0; i < n; i++){
if (arr[i] < 0) {
    negative ++;
} else if (arr[i] > 0) {
    positive ++;
} else if (arr[i] === 0) { 
    zero ++;
} 
}; 

console.log((positive/n).toFixed(6));
console.log((negative/n).toFixed(6));
console.log((zero/n).toFixed(6));
};
                
            

Diagonal Difference

Source: HackerRank
Date Solved: Sept. 23, 2022
Problem:

Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix arr is shown below:

                
1 2 3
4 5 6
9 8 9     
                
            

The left-to-right diagonal = 1 + 5 + 9 = 15. The right to left diagonal = 3 + 5 + 9 = 17. Their absolute difference is |15 - 17| = 2.

Function Description

Complete the diagonalDifference function in the editor below.

diagonalDifference takes the following parameter:

  • int arr[n][m]: an array of integers
Return
  • int: the absolute diagonal difference
Input Format

The first line contains a single integer, n, the number of rows and columns in the square matrix arr.
Each of the next n lines describes a row, arr[i], and consists of n space-separated integers arr[i][j].

Constraints
  • -100 <= arr[i][j] <= 100
Output Format

Return the absolute difference between the sums of the matrix's two diagonals as a single integer.

Sample Input
                
3
11 2 4
4 5 6
10 8 -12
                
            
Sample Output
                
15
                
            
Explanation

The primary diagonal is:

                
11
   5
     -12
                
            

Sum across the primary diagonal: 11 + 5 - 12 = 4
The secondary diagonal is:

                
        4        
    5
10
                
            

Sum across the secondary diagonal: 4 + 5 + 10 = 19
Difference: |4 - 19| = 15
Note: |x| is the absolute value of x

My Solution:
                
function diagonalDifference(arr) {
    let pDiag = 0;
    let sDiag = 0;        
    for (let i = 0; i < arr.length; i++){
        pDiag += arr[i][i];
        let arrReversed = arr[i].reverse();
        sDiag += arrReversed[i]
    } return Math.abs(pDiag - sDiag);
} 
                
            

A Very Big Sum

Source: HackerRank
Date Solved: Sept. 23, 2022
Problem:

In this challenge, you are required to calculate and print the sum of the elements in an array, keeping in mind that some of those integers may be quite large.

Function Description

Complete the aVeryBigSum function in the editor below. It must return the sum of all array elements.

aVeryBigSum has the following parameter(s):

  • int ar[n]: an array of integers .
Return
  • long: the sum of all array elements
Input Format

The first line of the input consists of an integer n.
The next line contains n space-separated integers contained in the array.

Output Format

Return the integer sum of the elements in the array.

Constraints
  • 1 <= n <= 10
  • 0 <= ar[i] <= 1010
Sample Input
                
5
1000000001 1000000002 1000000003 1000000004 1000000005
                
            
Sample Output
                
5000000015
                
            
My Solution:
                
function aVeryBigSum(ar) {
    let total = 0;
    for (let i=0; i < ar.length; i++){
        total += ar[i]
    } return total;
}
                
            

Compare the Triplets

Source: HackerRank
Date Solved: Sept. 23, 2022
Problem:

Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, awarding points on a scale from 1 to 100 for three categories: problem clarity, originality, and difficulty.

The rating for Alice's challenge is the triplet a = (a[0], a[1], a[2]), and the rating for Bob's challenge is the triplet b = (b[0], b[1], b[2]).

The task is to find their comparison points by comparing a[0] with b[0], a[1] with b[1], and a[2] with b[2].

  • If a[i] > b[i], then Alice is awarded 1 point.
  • If a[i] < b[i], then Bob is awarded 1 point.
  • If a[i] = b[i], then neither person receives a point.

Comparison points is the total points a person earned.

Given a and b, determine their respective comparison points.

Example

a = [1, 2, 3]

b = [3, 2, 1]

  • For elements *0*, Bob is awarded a point because a[0].
  • For the equal elements a[1] and b[1], no points are earned.
  • Finally, for elements 2, a[2] > b[2] so Alice receives a point.

The return array is [1, 1] with Alice's score first and Bob's second.

Sample Input
                
5 6 7
3 6 10
                
            
Sample Output
                
1 1
                
            
My Solution:
                                
function compareTriplets(a, b) {
    let score = [0, 0];
    for (let i =0; i< a.length; i++)
    if (a[i] > b[i]){
        score[0] ++
    } else if (a[i] < b[i]){
        score[1] ++
        }; 
    return score;
}