DEV Community

Ilya Nevolin
Ilya Nevolin

Posted on

Road to Genius: smart #19

Each day I solve several coding challenges and puzzles from Codr's ranked mode. The goal is to reach genius rank, along the way I explain how I solve them. You do not need any programming background to get started, and you will learn a ton of new and interesting things as you go.

coding challenge

Here's a new challenge with quite a lot of code, but only one bug that needs fixing 💧. You can solve this in several ways, the fastest method is by tracking variables, there are only a few potential variables that would fit the bug 💧. Both LM and RM are already used, and 💧 is unlikely to be any of these because those are arrays, and 💧 isn't used in an array-like fashion. The variable max appears to keep track of the max value, so 💧 isn't likely to be max, because max is no longer relevant at that stage.

The only remaining variable that's pretty much unused is V, it's also the value that the function returns, and since A = 4, then V cannot be zero; 💧 is very likely to be V.

coding challenge answer

You can take a few minutes to analyze the code closer, to understand what is going on. In a nutshell it's computing the sum of trap heights in a given array. A trap in this code, is identified by a value that's surrounded by two larger values (left and right of itself), as indicated by the arrow on the image below. In pseudo-code: TRAPi = min(left, right) - height. In this case there is only one trap, so A = 4, it is computed as such: A= V= min(6, 6) - 2

coding challenge extra

Join me on the Road to Genius and upgrade your programming skills, at

Top comments (0)