Berat Aras

Software Engineer

Blog

HackerRank Week 2: Easy Problems

5 min read

This week I solved 7 problems, pushing myself the whole way. The problems were easy level again. Some of them are so sneaky that you can have a conversation with your agent along the lines of "Weren't you ashamed at all to put this here and explain it?"

1 - Migratory Birds

In Migratory Birds, the bird types are given as numbers in an array. We are asked to return the number of the most frequently sighted type. If two types are sighted the same number of times, the one with the smaller number is chosen. What is returned is not how many times the type was sighted, but the number of the type.

I set up the counting part correctly on the first try. With reduce I stored how many times each type appeared in an object, then converted it to an array with Object.entries and sorted it by count from largest to smallest.

When only one type was left, for example in [3, 3, 3], the code crashed because numbers[1] did not exist. First I added an arr.length = 1 check, but this only caught a list with a single element. Then I put the numbers.length = 1 check before Object.entries, while numbers was still an object. Since objects don't have a length property, this check never ran at all.

function migratoryBirds(arr) {
  let numbers = arr.reduce((acc, number) => {
    acc[number] = (acc[number] || 0) + 1;
    return acc;
  }, {});

  numbers = Object.entries(numbers).sort((a, b) => b[1] - a[1]);

  if (numbers.length === 1) {
    return Number(numbers[0][0]);
  }

  if (numbers[0][1] === numbers[1][1]) {
    return Number(
      numbers[0][0] < numbers[1][0] ? numbers[0][0] : numbers[1][0],
    );
  }

  return Number(numbers[0][0]);
}

2 - Bill Division

In Bill Division, Anna and Brian split the bill. The dish Anna didn't eat is at index k. Anna's share is half of the total remaining after that dish is removed. If the amount Brian is charged, b, equals this share, "Bon Appetit" is printed; otherwise, the difference is printed.

My first approach was already correct: remove the uneaten dish from the array with splice, sum the rest with reduce, and divide by two.

In this problem there is no return to return. It ends with console.log:

function bonAppetit(bill, k, b) {
  bill.splice(k, 1);

  const a = bill.reduce((cal, curr) => cal + curr) / 2;

  if (b === a) {
    console.log("Bon Appetit");
    return;
  }

  console.log(b - a);
}

3 - Day of the Programmer

In Day of the Programmer, we are asked to return the date of the 256th day of the given year in the format dd.mm.yyyy.

Up to and including 1917 the Julian calendar applies; a year is a leap year if it is divisible by 4.

From 1919 onward the Gregorian calendar applies; a year is a leap year if it is divisible by 400, or divisible by 4 but not by 100.

1918 is the transition year and the answer is 26.09.1918. If it's a leap year the date is 12.09, otherwise 13.09.

By the way, I think this is a ridiculous problem, and just for show I also created a "canDivided" function.

function dayOfProgrammer(year) {
  let leapYear = false;

  const canDivided = (number) => year % number === 0;

  if (year === 1918) {
    return "26.09.1918";
  }

  if (year <= 1917 && canDivided(4)) {
    leapYear = true;
  }

  if (
    (year >= 1919 && canDivided(400)) ||
    (year >= 1919 && canDivided(4) && !canDivided(100))
  ) {
    leapYear = true;
  }

  if (leapYear) {
    return `12.09.${year}`;
  }

  return `13.09.${year}`;
}

4 - Drawing Book

In Drawing Book, we can start turning pages from either the front or the back of a book. We are asked to find the minimum number of page turns needed to reach the target page.

On my first attempt I calculated the number of turns from the difference between page numbers, that is, with p - 1 and n - p. But pages sit side by side in pairs. 2 and 3 are on the same pair, while 5 and 6 are on different pairs. So the same page difference can give a different number of turns. For n = 6, p = 3 I got 2, but the correct answer was 1. For n = 6, p = 5 I got 0, but the correct answer was again 1.

Then I tried to count, with for loops, how many times I would skip 2 pages from the front and from the back. The idea was logical, but my loop started from page 1 or page n and counted page by page. When the starting point landed in the middle of a pair, the count was off by one.

Unfortunately my weak math wasn't enough to come up with the formula for which pair a page is in. Apparently it's found with Math.floor(sayfa / 2). How is it found so simply, come on. There's no wizard like math. Anyway, turning from the front is Math.floor(p / 2), turning from the back is Math.floor(n / 2) - Math.floor(p / 2). Whichever is smaller gets chosen:

function pageCount(n, p) {
  const pPair = Math.floor(p / 2);
  const lastPair = Math.floor(n / 2);

  const lastDiff = lastPair - pPair;
  if (lastDiff < pPair) {
    return lastDiff;
  }

  return pPair;
}

5 - Counting Valleys

In Counting Valleys, a path made of U and D steps is given. U means one step up, D means one step down. Every descent below sea level that returns back to 0 is a valley. We are asked to find how many valleys were passed through.

I kept the location with a counter and tracked whether I was inside a valley by creating an isInValley variable, with my magnificent English:

function countingValleys(steps, path) {
  const pathArray = path.split("");

  let location = 0;
  let valleyCount = 0;
  let isInValley = false;

  for (let i = 0; i < steps; i++) {
    if (pathArray[i] === "U") {
      location += 1;
    }

    if (pathArray[i] === "D") {
      location -= 1;
    }

    if (location >= 0) {
      isInValley = false;
    }

    if (location < 0 && !isInValley) {
      valleyCount += 1;
      isInValley = true;
    }
  }

  return valleyCount;
}

6 - Cats and a Mouse

The easiest problem of the week. While solving it I felt very smart and looked in the mirror and praised myself. If you have trouble understanding the code, please send me an email, I'll help. 🙏🏻

In Cats and a Mouse, the positions of two cats and a mouse are given: x is Cat A, y is Cat B, z is the mouse. Whichever cat is closer to the mouse wins. If the distances are equal, the mouse escapes and "Mouse C" is returned.

I'll say something if you promise not to make fun of me; still, there was a critical point in the code. A cat can be to the left of the mouse or to the right. So the z - x difference can come out as -1 or 1, but both mean the same distance. So I immediately googled "Javascript convert negative number to positive" in caveman style. Thanks, Math.abs.

function catAndMouse(x, y, z) {
  const aCat = Math.abs(z - x);
  const bCat = Math.abs(z - y);

  if (aCat < bCat) {
    return "Cat A";
  }

  if (bCat < aCat) {
    return "Cat B";
  }

  if (aCat === bCat) {
    return "Mouse C";
  }
}

7 - The Hurdle Race

In The Hurdle Race, the height the runner can normally jump is k, and the heights of the hurdles are given in the height array. Each potion increases the runner's jump height by 1, and we are asked to find the minimum number of potions the runner must drink to clear all the hurdles.

By the way, once a potion is drunk, the jump height stays that way until the race is over. So there's no need to do a separate calculation for each hurdle.

In my code, runner holds the runner's current jump height and starts at k. I go through the hurdles in order. If a hurdle is higher than runner, I add the difference in potions to potion and raise runner to the height of that hurdle:

function hurdleRace(k, height) {
    let potion = 0;
    let runner = k;

    height.forEach((h) => {
        if(runner < h){
            const needPotion = (h - runner);
            potion += needPotion;
            runner += needPotion;
        }
    })

    return potion;
}

Bye 🫠