Berat Aras

Software Engineer

Blog

HackerRank Week 1: Easy Problems

9 min read

This week I worked on 6 HackerRank problems with JavaScript. My developer ego was flattened. The problems I solved are at the "easy" level on HackerRank, but it feels to me like the simpler the problem gets, the more I struggle. With nested for loops, especially when the array I'm walking through is an array of numbers, my mind flies off to faraway lands. i this, i's j that, whatever... Many times I felt stupid, no lie, and honestly I think I am stupid. I was already struggling a lot with these problems before AI, because we constantly use libraries and frameworks, but I feel that in the age of AI, if we don't do something about reading and writing code, we will get dumber and dumber.

After all, in the age of AI, if we need to understand what agents do and make a judgment about it, we somehow must not lose this practice. Okay, let AI build your big applications. Yes, they do it quite well. Wasting time writing code may be pointless. But when they catch a vulnerability in production later on, they will blame us, not the agent. We all know this. So wouldn't it make sense, in an era like this, to improve our algorithm and code-reading skills? Since to me the answer to this question falls in the "makes sense" category, I started on the HackerRank problems.

Also, I'm having fun. I still love problem solving very much, but while solving these problems this week I realized how much I had missed solving problems with code.

1 - Divisible Sum Pairs

Divisible Sum Pairs asks the following: pick two numbers from different positions in the array. If their sum is divisible by k with no remainder, count it as a pair. Each pair is counted only once.

Where I got stuck was the phrase "two different elements." On my first attempt I understood it as different values. But what has to be different is the positions, that is, the indices. The values can be the same. For example, in the array [3, 3] there are two 3 values, and they are separate elements.

With this misunderstanding, I tried to check for duplicates by value. I needlessly complicated things with approaches like pairs.every and sorted comparison. The some that was suggested to me didn't work either, because it also looked at the value and didn't solve the real problem. When the explanations confused me further, the first session was left unfinished.

Then I solved the problem my own way. The outer loop takes each number with i. The inner loop starts from j = i and prevents a number from being paired with itself with the i !== j check. If the sum is divisible by k with no remainder, I increment the counter. I chose to start from i and do the check separately. This code passed Submit:

function divisibleSumPairs(n, k, ar) {
  let divisibleCount = 0;
  
  for(let i = 0; i < n; i++){
    for(let j = i; j < n; j++){
        if(i !== j){
            const total = ar[i] + ar[j];
        
            if(total % k == 0){
                divisibleCount += 1;
            }
        }
    }
  }
  return divisibleCount;
}

2 - Sales by Match

In Sales by Match, the color of each sock is given as a number. We are asked to find how many pairs of the same color there are. A leftover single sock doesn't count as a pair.

The first thing that came to my mind was deleting matched socks from the array. But when I deleted, the indices shifted. I thought of solutions like a reverse loop, but things got even more tangled.

Actually, I had earlier written a solution that counted with reduce, but I had abandoned it because it felt long. This time I learned with small examples. The line count[el] = (count[el] || 0) + 1 starts from 0 if that color hasn't been counted before and adds one. That way an object is built that holds how many times each color appears.

The second important point was that to find the number of pairs, I needed % not Math.floor(adet / 2). For example, 5 socks give 2 pairs, and the remaining 1 sock isn't counted. For some reason I tried to use % and increased the time even more. In my final code, I go through the count of each color with Object.values and sum up the pairs:

function sockMerchant(n, ar) {
    const elements = ar.reduce((count, el) => {
    count[el] = (count[el] || 0) + 1;
    return count;
  }, {});

  let pairCount = 0;

  Object.values(elements).forEach((piece) => {
    if (piece > 1) {
      pairCount += Math.floor(piece / 2);
    }
  });

  return pairCount;
}

In both problems the difficulty wasn't in the code itself. In the first I had misread the problem, and in the second I hadn't fully understood the tool I was using.

3 - Subarray Division (The Birthday Bar)

In Subarray Division there is an array of chocolate squares. d is the total we want to reach, and m is the length of the piece. We count how many pieces there are that consist of m adjacent squares and whose sum is d. These pieces can overlap each other.

The first place I got stuck was what d and m meant. The first explanation I asked the AI for didn't make it clear. It clicked when it was explained with the example of February 3rd: the day is the sum, and the month is the piece length.

Then I thought about shifting the starting point by m at each step. But since the pieces can overlap, you need to advance one step each time. When it's [1, 2, 1] and m = 2, both [1, 2] and [2, 1] are counted as separate pieces.

I wrote the code with slice(i, i + m) and reduce. The first version had a length === 0 check, so short pieces left at the end of the array were also being counted. In the counterexample s = [1, 2], d = 2, m = 2, the single-element [2] at the end shouldn't be counted and the answer should have been 0. When I saw this, I changed the check so that it exits the loop when length < m.

function birthday(s, d, m) {
  let count = 0;
  for (let i = 0; i < s.length; i++){
     const current = s.slice(i, i + m);

     if(current.length < m){
      break;
     }
     
     const total = current.reduce((acc, curr) => acc + curr, 0);

     if (total === d){
        count += 1
     }
  }
  return count;
}

4 - Kangaroo

In Kangaroo, two kangaroos start jumping at the same time from points x1 and x2. One advances v1 with each jump, the other v2. We need to say YES or NO as to whether they will land on the same point after the same number of jumps.

My first loop condition was x1 > x2 || x2 > x1 || x1 === x2. Since this condition is always true, the loop never ended once the kangaroos had passed each other. Then I worked on these: ending the loop based on position rather than a fixed number of rounds, seeing that when the speeds are equal the gap never closes, and taking into account that the faster kangaroo can pass the other without landing on it.

In my final code, if the kangaroo in front is at least as fast as the other, I return NO right at the start. Then I advance both together until the one behind catches up, and check whether they are at the same point:

function kangaroo(x1, v1, x2, v2) {
    if ((x1 > x2 && v1 >= v2) || (x2 > x1 && v2 >= v1)){
        return "NO";
    }
    
    while(x1 < x2){
     x1 += v1;
     x2 += v2;   
    }
    
    if(x1 === x2){
        return "YES"
    }
    
    return "NO";
}

5 - Between Two Sets

Between Two Sets counts numbers that satisfy two conditions. The number must be divisible with no remainder by every element of array a, and must divide every element of array b with no remainder. For example, for a = [2, 4] and b = [16, 32], these numbers are 4, 8 and 16.

Since I don't know GCD and LCM well, I chose the brute-force route. The outer loop walks through candidate numbers, and inside I check the two arrays in turn. The places where I got stuck:

  • I mixed up the candidate number with the index in the array.
  • I thought I had to match a[i] with b[i].
  • I mixed up the direction of the division: the correct ones are aday % a[j] and b[d] % aday.
  • I mixed up the range the candidates should be in and the array lengths.
  • I only later settled on the idea that every element must satisfy the condition, rather than a single element satisfying it.
  • I learned that once available becomes false, I must not set it back to true on a successful check.
  • I mixed up b[d] % d and b[d] % i.

In my solution, I first took the largest number in the two arrays with Math.max. Then I opened a for loop that goes up to that number and put two separate loops inside it that check the two conditions. At first I tried to add the numbers satisfying the condition to the mix array inside the lower loops. This naturally led to the same numbers being added over and over. Yet the real goal was to find out, with a single check, whether the candidate number i satisfied the conditions in both arrays together. So right below the first loop I created the variable available = true. (The AI suggested this variable, no point lying :D but understanding why we did it this way in the end is the important part for me.) After all the checks are done, if available is still true, that number was one of the numbers we were looking for:

function getTotalX(a, b) {
    const length = Math.max(...a, ...b);
    const mix = [];
    
    for(let i = 1; i <= length; i++){
        let available = true;
        for(let j = 0; j < a.length; j++){
            if (i % a[j] !== 0){
                available = false;
            }
        }
        
        for(let d = 0; d < b.length; d++){
             if (b[d] % i !== 0){
                available = false;
            }
        }
        
        if(available){
            mix.push(i);
        }
    }
    
    return mix.length;
}

6 - Apple and Orange

In Apple and Orange there is a house, an apple tree and an orange tree. The house stands between s and t. The distances of the fruits falling from the trees, measured from their tree, are given. We are asked to print the number of apples and oranges that land on the house on separate lines.

Where I got stuck was the meaning of the distance. At first I took the value d = 3 to be the point where the fruit fell, and since the house is between 7 and 10, I thought the fruit stayed outside. But 3 was the distance from the tree. If the tree is at 5, the fruit falls at 5 + 3 = 8, so on the house. Once I understood this, I figured out negative distances too: 5 + (-2) = 3, the fruit falls to the left of the tree. The result is printed with console.log, not with return.

At first I wrote two separate counters and two separate loops for apples and oranges. When the AI said the two loops were almost the same, I shortened the code. I wrote a helper function called countFruit that takes the fruits and the tree's position and counts those that land on the house. I included the endpoints with <= and >=.

function countApplesAndOranges(s, t, a, b, apples, oranges) {
    const countFruit = (fruits, treeLocation) => {
        let count = 0;
        for (let i = 0; i < fruits.length; i++){
            const dot = fruits[i] + treeLocation;
            if(dot <= t && dot >= s){
                count += 1;
            }
        }
        return count;
    }
    
    console.log(countFruit(apples, a));
    console.log(countFruit(oranges, b));
}

Looking back on this week, most of the places where I struggled weren't the code itself. Either I had misread the problem or I didn't fully know what the tool I was using did. I think this matters in the age of AI. To be able to understand and judge the code agents write, we must not lose this practice. Learning frameworks and new technologies is of course very valuable in terms of speed, but when the agent era comes on top of using them, our ability to read code and solve problems on code is gradually dulling. Even if the problem is easy, and even if it looks like crumbs next to the projects we've done so far, we must not lose this reflex. In the second week I'll continue with easy problems again.